Does appending a reference to an external script imply immediate loading?
If I run the following code,
document.getElementsByTagName('head')[0].innerHTML +=
'<scri开发者_StackOverflowpt src="http://..."></script>';
...am I guaranteed that the script is loaded before the next line of code is executed?
In other words, if the next line accessed something in the external script, would it cause an error, or would it work?
This is a very strange way to add a script dynamically. The DOM methods used here imply a loaded document, but the change of innerHTML
suggests that you're trying to modify the document source, which generally doesn't work after the document has loaded.
There are two more customary ways of using JS to pull in more JS:
Before the document is done loading, you can
document.write('<script src="' + scriptSource + '"></scri' + 'pt>');
In this case, the script will be loaded immediately after the conclusion of the current
<script>
block (but not until then - so subsequent JS statements in the same block will run fitst).After the document is loaded, using
document.write
doesn't work, since it will destroy your existing document, so instead you can use DOM methods to construct and append ascript
elementvar scriptEl = document.createElement('script'); scriptEl.src = scriptSource; document.getElementsByTagName('head')[0].appendChild(scriptEl);
In this case, the script loading will happen asynchronously - you can attach an
onload
listener to the constructedscript
element to be notified of when it gets loaded.
Yes, but any code bound to the window.load or document.load event will not have been run yet.
精彩评论