Upon defer attribute MDN says:
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. The defer attribute should only be used on external scripts.
On DOMContentLoaded MDN also says:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets...
So DOMContentLoaded is fired before CSSOM is ready. This means deferred scripts are executed before CSSOM is ready. But if that's true the scrips must not be able to get correct CSS property values and must not apply CSS correctly. But it's not true, we know all deferred scripts work well.
So is MDN documentation technically incorrect?
Where can I find the official documentation of DOMContentLoaded`? I searched in https://dom.spec.whatwg.org/ but couldn't find it.
P.S: Please note that google says that CSSOM is built before executing any inline javascript
But Google is technically incorrect. Inline JavaScript gets executed before CSSOM is ready. And from my tests, I found that MDN is correct and if js files(both deferred and non-deferred) are downloaded before CSS files(or js is inline) then js is executed before CSSOM is ready. So js might handle styles incorrectly. To avoid that we need a forced reflow before all js logic.
So if a user visits our website with all js required already cached and CSS not cached OR js gets downloaded before CSS then (s)he might see an incorrectly rendered page. To avoid this we should add force reflow in all our websites' js files.
I didn't really read the spec though. The following are based on actual behaviors of Chrome (observed on Chromium 68, Ubuntu). Behaviors may vary among browsers, if they were just undefined in specifications. For example in 2010 scripts don't always wait for proceeding stylesheets. I assume agreements had been achieved and behaviors had been standardized over the years.
The defer scripts are executed after domInteractive, before domContentLoaded; it's sequential.
domInteractive and domContentLoaded are two timestamps which could be viewed in Chrome devtools' Performance (previously Timeline) tab. Probably also in other similar tools, but I haven't tried.
domInteractive is the point when HTML parsing and initial DOM construction are finished (and all "sync" scripts have finished executing). document.readyState changes from 'loading' to 'interactive'; a readystatechange event fires on document accordingly.
All defer scripts are executed in their appearing order. Then comes domContentLoaded, a DOMContentLoaded event fires on document.
DOM & CSSOM construction don't rely on each other; but sync scripts may introduce dependencies.
Each sync script, internal or external, waits for preceding stylesheets to be parsed (of course, after fetched).
Yes, sync scripts are not blocked by subsequent stylesheets. MDN and Google and other articles say "scripts depend on CSSOM to be ready"; they (probably) didn't mention that only preceding parts are depended.
P.S: Please not that google says that CSSOM is build before executing any inline javscript
Google didn't say that (at least, as of the time I read this article).
On the contrary, before one sync script is fetched (if external) and executed, any code following it, HTML, stylesheets or other scripts, can't be parsed/executed/constructed. They block anything subsequent to them.
So, in specific cases, eg. without sync scripts, DOMContentLoaded event may fire before or after CSSOM is ready. That's what MDN means by saying "without waiting for stylesheets".
defer/async scripts don't care about stylesheets at all.
Different from sync scripts, defer/async scripts don't wait for preceding stylesheets, and don't block subsequent stylesheets/scripts either. They are removed from those "dependency chains" completely. You can't rely on any proceeding stylesheets to have been parsed.
The differences between defer/async:
as stated above, defer scripts have predictable execution time; the DOM has been ready. They are also promised to execute in order.
Update:
defer scripts are added to the end of the list, says W3C's spec (the 20th item)
(also in WHATWG's spec)
async scripts have no promise on execution order; each async script would be "queued to execute" as soon as it is fetched; once the render process is idle, they are executed. (To be exact, different types of resources have different priorities. The spec provides precious requirements)
These should well explain hinok's two examples, the former async (from Google) and the latter defer。
I don't have much experience on working with CSSOM at page loading (I do operate on DOM at page loading, though), so I can't provide reliable advises. It seems "load event on window" or "force reflow early" might work.
I use deferred script loading. There was a lengthy technical explanation from some guy who is a well known website performance guru. He clearly states that deferred is the way to go (for this and that technical reason, backed by all kinds of data and charts, that many people seemed to feel was wide open for debate, re: async).
So I started working with it. Deferred scripts have the advantage of downloading async, but executing in the order presented, which can be a problem with async (e.g. you can load your app bundle before your vendor bundle because you don't control the execution order of async scripts just by saying "in this order").
However, I found out right away that although this solves that problem, this could mean, depending on how you grab your bundles, the CSS bundle isn't loaded. So you can end up with unstyled content, depending on how you set things up. Note that for defer, they also say that you shouldn't be writing to the dom etc. in those scripts (which again makes sense in terms of your documentation).
So it would seem your documentation is correct. The effect is easily reproduced.
How do I get out of it; the most basic way, is like this:
<script src="css.bundle.js"></script>
<script src="vendor.bundle.js" defer></script>
<script src="angular.bundle.js" defer></script>
<script src="app.bundle.js" defer></script>
This makes sure that the css loads in first, so your home page and so on will show up nicely, and also ensures that (although all three are loading async), that app.bundle will execute last, ensuring all other dependencies are in order.
So, you take the absolute bare minimum of CSS required to kick over the app, create that as a bundle, and load it first, before anything. Otherwise you can bundle in your CSS per module/component, and so on.
There's a lot more to this topic and I could probably be doing more, but again (I will try to find the reference), this was overtly recommended by that performance wizard, so I tried it and it seems pretty effective to me.
Edit: Fascinating, while looking for that reference (which I haven't found yet), I went through a handful of "experts" on the subject. The recommendations differ wildly. Some say async is far superior in all regards, some say defer. The jury really seems out on the topic, overall I'd say it probably has more to do with exactly how you build out your scripts than whether one is actually better than the other.
Edit again: Here's some more evidence. I ran a performance analyzer on a stub website using the above simple loading sequence, deliberately making the scripts naive so they'd be visible in a timeline.
Here's an SS of the result: there are four yellow boxes here. The first three are the evaluations of the scripts. The fourth one (when you mouse over it in the tool, this is just the SS remember) is the DOMContentLoaded event (the one with the red corner).
DOMContentLoaded can be fired before CSSOM, source
The domContentLoaded event fires shortly after the HTML is parsed; the browser knows not to block on JavaScript and since there are no other parser blocking scripts the CSSOM construction can also proceed in parallel.
Article on Google Developer describes async instead of defer but in the case of your question, it doesn't change anything because based on Steve Sourders article on perfplanet
DEFER scripts execute after DOM Interactive.
and his comment under his article
[...] the spec says that DEFER scripts run after domInteractive but before domContentLoaded.
You can make your own experiment, look below for code using defer and timeline
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.3/angular-material.css">
</head>
<body>
<h1>App</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.js" defer></script>
</body>
</html>
Related
In this post:
Why google is using the term "Render-Blocking JavaScript"?
#jaffa-the-cake is asking in a comment to someone:
"Which piece of documentation do you consider incorrect?"
Let's take for example this documentation:
https://developers.google.com/speed/docs/insights/BlockingJS
And now let's take for example what they are saying about "defer":
The loading and execution of scripts that are not necessary for the initial page render may be deferred until after the initial render or other critical parts of the page have finished loading. Doing so can help reduce resource contention and improve performance.
Note that the article is about "Remove Render-Blocking JavaScript", so with the word "may" they mean that you COULD use defer.
With "defer" on a script tag, you will NOT defer "the execution until after the initial render of the page have finished loading". It can be the case, but not necessarily.
"Defer" will defer the execution until after the initial html is in the DOM, but that's something different than "render". The execution will take place after the (preceding) html is in the DOM and before DOMContentLoaded, but that does not mean: "render of the page have finished loading". It would be correct if they would use the term "html parsing of the page have finished".
An example which confirms the theory of above:
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
Some HTML line and this is above the fold
<script src="script.js" defer></script>
</body>
</html>
SCRIPT.JS (from cache!)
// Synchronous delay of 5 seconds
var timeWhile = new Date().getTime();
while( new Date().getTime() - timeWhile < 5000 );
In case the browser will take script.js from cache then "Some HTML line and this is above the fold" will be shown AFTER 5 seconds! So that means the initial render of the page have NOT finished loading yet (while using defer). So in my opinion that means the documentation is incorrect.
p.s. Without script.js from the cache, a browser will have time to finish rendering of the preceding html. The file script.js first has to be downloaded, so that's what gives the browser extra time. With caching, there is less time between "done parsing html" and starting with the "javascript execution", so then there is a chance that "javascript execution" already starts before "finishing rendering of the preceding html". So in case of speed gain, you could even consider in this example to disable caching, so the rendering of the preceding html will be faster.
I have a lot more tests / examples which proves other parts in other documentation (about rendering) of Google are incorrect (in my opinion), but i will keep it clear in this post by using 1 example.
If you are disagree with me, please don't give only a negative reputation, but at least give a comment why you think it's incorrect and which test you did to confirm it. I'm already trying to convince some people at Google that they are incorrect in my opinion, but they are kind of offended by that. Of course i would not say that they are incorrect if i didn't put a lot of time / energy / testing in it and if i would be pretty sure about it. Until now they are saying to me: "consider that the misunderstanding may be yours", so i feel like a small boy "fighting" against a big wall. For me it's not about to get right in the first place, but i see so many people around me (they are already for many years working in IT) struggling with the subject rendering and i can understand it, because the documentation about it is very confusing. That's also why i dived deeper into it, because it was also getting too confusing for me, so i wanted to understand it better.
And if i am wrong, just convince me with arguments and i am the first who will say i was wrong.
After re-reading your question and the linked quote I'm seeing where you are coming from, and why this quote can be misleading. For reference let me put the quote below with the title included:
Defer loading of JavaScript
The loading and execution of scripts that are not necessary for the initial page render may be deferred until after the initial render or other critical parts of the page have finished loading. Doing so can help reduce resource contention and improve performance.
You already understand this, but I'll link it for a reference on how defer works.
As you mentioned, yes the execution of JavaScript in defer and in general is always render blocking, and rather defer does not block the DOM parser.
The reason why the quote is misleading/confusing is because of the sections in bold:
The loading and execution of scripts that are not necessary for the initial page render may be deferred until after the initial render or other critical parts of the page have finished loading. Doing so can help reduce resource contention and improve performance.
The section "The loading and execution of scripts that are not necessary for the initial page render may be deferred until after the initial render". While not an incorrect statement, is misleading because but the performance gain is really directly due to the parser not getting blocked.
This can be clearly shown using the official documentation on defer
A more direct and more clear way to describe this would be as you mentioned:
The loading and execution of scripts that are not necessary for the initial page render may be deferred until after the initial parsing or other critical parts of the page have finished loading. Doing so can help reduce resource contention and improve performance.
That makes it clear that the performance gain is due to the parser being deferred. It also is more inline with how defer specs describe it and the befits of defer:
If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete. (W3C)
Once upon a time, there were many heated debate on <script> in <head> or <body>.
Many SO posts had already pointed out the best practice / rule of thumb is to place the <script> before end of <body>for not blocking the html parser, resulting faster first screen paint and quicker DOM access for client, and thus a better UX.
This must be a duplicate╰(‵□′)╯
Wait ... <script> can be deferred now, actually for quite a while !
Old posts said
deferred script may results JS dependency issues
No, it won't. It retains the order on execution immediately when the DOM gets parsed.
It doesn't work cross vendors
Yes, it once was, but today it's almost supported by all major browser vendors: http://caniuse.com/#search=defer, besides may have some problem with IE<10 as the comments point out.
However, the benefits it offers seem obvious, at least to me, as it downloads the script in parallel at earlier time(before start parsing the DOM), thus no need to request the script later and shortens the time it takes to bring the whole page interactive.
To be short, this question is similar to: Any good reason not to use
<head>
...
<script src='cdn/to/jquery' defer>
<script src='cdn/to/bootstrap' defer>
<script src='script/depends/on/jqueryandbootstrap' defer>
</head>
instead using this:
<body>
...
<script src='cdn/to/jquery'>
<script src='cdn/to/bootstrap'>
<script src='script/depends/on/jqueryandbootstrap'>
</body>
note: This might be an "ancient" topic with lots of discussions. However, as web technology moves really fast, browser vendors align better and more consistent with new web specs, many old stackoverflow answers may not keep up-to-date.
Yes, but only because you're using jQuery.
jQuery doesn't work with defer because it tries to fire as soon as the page becomes interactive. They can't fix it any time soon (I raised that bug over a year ago) because changing the ready behaviour to work with defer will break lots of components that rely on jQuery's ready event firing on interactive (i.e. before deferred scripts have finished loading).
If you're using a more modern framework (React, Angular 2, Polymer, Vue, or just about anything else) then go for it - or even go to the next step and use <script type=module in new browsers and a legacy bundle in <script nomodule defer... for IE.
As noted here you should take browser support into account, as some of them don't really support it. There are also some well known bugs in some versions like this one in IE<=9.
If your goal is not to support old browsers (find full support list here) then there is no real reason for not picking defer today.
I am sure I don't fully understand this problem, but it seems that we are seeing strange behavior on IE9 on my project, somehow related to out-of-order execution of JavaScript that has been injected via calls to document.write, e.g.:
document.write('<scr'+'ipt type="text/javascript" src="'+file1+'"></src'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="'+file2+'"></src'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="'+file3+'"></src'+'ipt>');
My limited Google research suggests that IE9 will execute scripts injected in this manner in a different order from other browsers (notably, Firefox and Chrome). Is there a better way to achieve what we're going for here, which will ensure the same execution order by all browsers?
I take that back: we don't really care about all browsers, just Chrome and IE9.
Use a script loader (like the one I wrote: LABjs), which will normalize all the different quirks of loading across the various browsers. And bonus: it doesn't use that god-awful document.write(). LABjs will let you load all your scripts asynchronously (in parallel), but make sure they execute in the proper order. Sounds like basically exactly what you want.
I guess you could chain the onload event of one to start the load of another:
var newJS= document.createElement('script');
newJS.onload=function() {alert("done")} //or call next load function
newJS.src="..."
document.body.appendChild(newJS)
So the advantage of writing script tags this way is that they are loaded asynchronously. I don't know about browser nuances about exactly how this is done but I would have thought they would be executed when they're downloaded, in no specific order. Similar to the behaviour of the HTML5 async attribute.
There's another HTML5 attribute defer which instead makes scripts execute in order, but in a non blocking way. You could try adding that into your generated <script> tags. IE9 partially honours it.
I have made a little script, exactly for this purpose:
https://github.com/mudroljub/js-async-loader
In short, it loads all your scripts asynchronously, and then executes them consequently. It looks something like this:
for (var lib in libs) {
loadAsync(lib);
}
And you don't need document.write();
I'm using a framework which features auto-connecting to server on page load. I can disable it by passing options arguments, but the line that confuses me is this:
You can prevent this initial socket from connecting automatically by disabling io.sails.autoConnect before the first cycle of the event loop elapses.
My questions are:
When does the first cycle of the event loop elapses?
Is this behaviour the same across ALL modern (IE9+) browsers?
I have a bunch of scripts (in <body>) loading between the lib and my entry file. Does this affect when the first cycle elapses? EDIT: Yes, it does.
How can I ensure my code runs before the first cycle elapses?
Is this kind of implementation of auto-connect considered good practice?
The documentation for the source file is a little more explicit; it says "This can be disabled or configured by setting io.socket.options within the first cycle of the event loop."
Basically what's happening is that there exists within the library a setTimeout(fn, 0) call, which is idiomatic for starting a parallel process. However, in the JS standards it's explicitly stated that JS is single-threaded: in other words, even though setTimeout and setInterval are asynchronous they are not actually parallel in the sense that any of their code will be executing simultaneously with any other code. So they wait until the current function is over before they execute. This queueing mechanism is known as the JavaScript event loop.
I believe that what you are asked to do by the script author is to modify the source to include the relevant change, perhaps at the bottom of the file for your convenience.
It is also likely that a similar effect will be achieved by putting a <script> tag underneath the one that loads the given JS. This has not been explicitly standardized by HTML 4, but may be implicitly standardized in the new HTML 5 spec (it's a complicated interaction between different parts of the specs).
In terms of HTML5, it looks like the current specs say that there is a afterscriptexecute event and a load event which occur immediately after any remote script is loaded (or, if it's an inline script, the load event is scheduled as a task -- I am not sure when those occur). So you might be able to guarantee it without modifying the script by instead doing:
<script>
function do_not_autoload() { /* ... */ }
</script>
<script onload="do_not_autoload()" src="./path/to/sails.io.js"></script>
but I'm not sure what the compatibility table for script#onload is going to look like.
I made you a jsfiddle which can be used to grab a 'fingerprint' for different browsers to get an idea of what evaluation orders are out there in the wild. The * is the document.body.onload event. On my system it produces:
Firefox 32.0.3 : cafdbe*
Chrome 37.0.2062 : cafd*be
IE 11.0.9600 : cafd*be
In other words,
I am trying to figure out a problem with some code I have inherited.
I have an HTML page with
<script type="text/javascript" src="file1.js" defer="defer"></script>
<script type="text/javascript" src="file2.js" defer="defer"></script>
</body>
</html>
file1.js has
FOO = {
init : function () {
var bar = BAR;
}
}
$(document).ready(FOO.init);
file2.js has
var BAR = {
}
Because of the defer attribute on the elements, is it safe to assume that when the .ready() calls FOO.init() that BAR may still be undefined at that point b/c the code in file2.js hasn't executed yet because of the deferred execution?
This would match a bug I am trying to track down (only occurs sporadically in IE), but I really want to understand why this is happening before I work on a solution. I have no idea why the original developer used defer, other than a cryptic commend about "he had to" do it this way.
Defer should cause the script to be added to a queue that is processed after the page is completely loaded. According to the spec deferred scripts should be added to the queue in the order they came onto the page.
However different browsers have done slightly different things with the order. IE seems to run defer scripts in the order they finished loading rather than the order they occurred on the page. So you seeing the error sporadically because sometimes it's loading them in the right order and sometimes not.
See this post on hacks.mozilla.com for a more exhaustive explanation and examples of how different browsers handle the ordering of the defer queue.
Deffering in javascript gives preference to the browser of when to interpret the script, in some optimal conditions like with chrome the script is downloaded while the page is being loaded then parsed and interpreted. If you use defer like the above you can never be certain which script is loaded first or when the interpretation is complete.
BAR could be undefined on one page load and be defined on the reload (cached) or the second script was loaded first.
To test this try make a change to one of the scripts to force a new download and interpretation and see what race conditions exist.