Reputation: 29977
I'm scratching my head at an issue I recently faced when appending an HTML block which included a <script src=[...]>
. I've created a js fiddle to show the issue (or I should say my poor understanding of JS).
When the following html block is added to a page, it looks like the actual loading and and execution of the script 'gHnukrbe.js' is delayed. The script that is loaded, is a 'jwplayer cloud-player', which defines the function jwplayer
. When the code is executed, it outputs is jwplayer declared? undefined
<div id="output">
<script type="text/javascript"
src="https://cdn.jwplayer.com/libraries/gHnukrbe.js"></script>
<script>
$("#output").append("<p>is jwplayer declared? " + typeof jwplayer + "</p>");
</script>
</div>
After the code that injects this block of html, I added a delayed function which checks again if jwplayer is declared and voila, there it is. The following snippet outputs is jwplayer declared T+5s? function
setTimeout(function() {
$("#output")
.append("<p>is jwplayer declared T+5s? " + typeof jwplayer + "</p>");
}, 5000);
So I'm trying to figure out how browsers load the script in this situation, as I had the impression that the parser would stop to load the JS file completely before executing any other javascript, but it's obviously now doing this.
(Minimal answers with a link to a more in depth explanation are welcomed!)
To add to the mysterious mystery, if the JS file is hosted on the same server from where the page is loaded, this issue doesn't show up. Unfortunately, I cannot show this on JSFiddle.
Upvotes: 3
Views: 54
Reputation: 13353
Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order.
We can explicitly mark them as not async. However, adding async='false'
does not work. Just like <input type="checkbox" checked="false" />
will not uncheck the box. You will have to programatically create the script elements instead of appending a block of HTML.
For full explanation: https://www.html5rocks.com/en/tutorials/speed/script-loading/
Upvotes: 1