How do I ensure my javascript only executes after all external <script src="..."> have loaded their contents?
Our website uses the G开发者_StackOverflow中文版oogle API to execute google searches. The problem I am experiencing is that the following code fails...
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1');
</script>
It fails with the following error message:
'google' is undefined
My guess is that this is happening because the Google API has not loaded completely before the script executes.
Should I use JQuery's document.ready? I read that this will start executing script when the DOM has finished loading. I assume this does not include loading external resources like scripts, stylesheets and images?
No-repro
<script src="http://google.com/jsapi"></script>
<script>google.load("jquery", "1");</script>
<script>alert($);</script>
It does work, there is no need for an API key.
Can you check the request it is making? (with Firebug or something) It might be a problem with your connection... That is why there is a fallback for jQuery you can implement. As for the loader you will have to check why the request is failing.
Unless you specify defer
or async
attributes, <script>
s always load and execute sequentially; the second script will only be executed after the first one has loaded and executed. (Note that this doesn’t necessarily mean you’ll already notice a difference at this point; for example, I could execute the script window.onload = function() { alert(42); };
right now, but I will only see its result when the onload
event fires.)
If you’re using this code:
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('search', '1');
</script>
And you get an error message saying google
is undefined, it means the first script failed to load.
精彩评论