How and when do browsers implement real-time changes to a document's DOM?
My website dynamically embeds an external Javascript file into the head tag. The external Javascript defines a global variable myString = "data". At what point does myString become accessible to Javascript within the website?
<html>
<head>
<script type="text/javascript">
myString = null;
external = document.createElement("script");
//externalScript.js is one line, containing the following:
//myString = "data";
external.setAttribute("src", "externalScript.js");
external.setAttribute("type", "text/javascript");
document.getElementsByTagName("head")[0].append(external);
alert(myString);
<script>
</head>
<body>
</body>
</html>
This code alerts null开发者_StackOverflow中文版 (when I thought it would alert "data") in Chrome and IE, even though the DOM has loaded in externalScript.js at this point. When is externalScript.js actually evaluated by the browser and at what point do I have access to the new value of myString?
You can access it when the onload
event fires for that script element, like this:
external = document.createElement("script");
external.onload = function() { alert(myString); };
script.onreadystatechange= function () { //for IE, the special kid...
if (this.readyState == 'complete') alert(myString);
}
external.setAttribute("src", "externalScript.js");
external.setAttribute("type", "text/javascript");
document.getElementsByTagName("head")[0].appendChild(external);
This just attaches a function to run once that script has loaded, execute any code that depends upon the script in there. Correction to previous answer: as seanmonstar points out in comments (thanks!), you do indeed need an IE exception here again, because it's a bit "special"...
精彩评论