I created the example below where the page loads the temp.js dynamically at the bottom of the HTML page. The temp.js has a little sleep function which binds up browser for 3 seconds before logging ‘Script Loaded’. At the very bottom of the HTML page it logs a ‘Page Loaded’
Now, knowing what I know about browsers, downloading resources and the single threaded nature of JS I thought this would happen.
- HTML is displayed
- console.log ‘Page Loaded’
- About a three seconds wait whilst temp.js does it stuff
- console.log telling me ‘Script Loaded’
but what in fact happens is this
- console.log ‘Page Loaded’ (almost instantly)
- Blank page for about three seconds
- HTML is displayed and console.log telling me ‘Script Loaded’
Is this the behaviour you would have expected?
function sleep (ms) {
var now = (new Date()).getTime ();
while ((now + ms) > ((new Date()).getTime ())) {
}
}
sleep (3000);
console.log ('Script Loaded');
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>querySelectorAll</title>
</head>
<body>
<ul>
<li><a href="">One</a></li>
<li><a href="">Two</a></li>
</ul>
<div id="nick">
<img src="image.png" alt="" width="10" height="10" />
<img src="image.png" alt="" width="10" height="10" />
<img src="image.png" alt="" width="10" height="10" />
</div>
<!-- <script type="text/javascript" src="temp.js"></script> -->
<script type="text/javascript">
(function() {
var e = document.createElement('script');
e.src = 'temp.js';
e.async = true;
document.getElementsByTagName("head")[0].appendChild(e);
})();
</script>
<script type="text/javascript">
console.log('Page Loaded');
</script>
</body>
</html>
What happens
<script>block 1 is parsed and it adds a new script tag to the<head><script>block 2 is parsed and it logs page is loaded<script>block in head is parsed and it runs your blocking sleep function<head>block has finished parsing and it renders the<body>Change
document.getElementsByTagName("head")[0].appendChild(e);To
document.getElementsByTagName("body")[0].appendChild(e);And the HTML page will load first.
The problem is that all scripts in the
<head>have to be loaded and run before the HTML body is rendered