Any good reason not to use <script defer> TODAY? - javascript

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.

Related

Google is wrong about defer?

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)

Are deferred scripts executed before DOMContentLoaded event?

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>

Chrome doesn't take new CSS and Javascript programming

I'm having an issue with updating a web application in Chrome. It’s an ASPX site, but I don’t believe it’s relevant to this conversation. The issue is that our clients don’t get the latest programming in Chrome, because most of the time, it fails to release Javascript and CSS programming from memory, then proceeds to cause all kinds of mayhem while in use.
I tried placing this piece of code in the <head>, like many have suggested, but it doesn’t work all the time.
<script type="text/javascript">
function reload_js(par_src) {
src = $('script[src$="' + par_src + '"]').attr("src");
$('script[src$="' + par_src + '"]').remove();
$('<script/>').attr('src', par_src).appendTo('body');
}
reload_js("../../global/scripts/global_scripts.js");
reload_js("scripts/main.js");
reload_js("scripts/tabs/jquery.ui.core.js");
reload_js("scripts/tabs/jquery.ui.widget.js");
reload_js("scripts/tabs/jquery.ui.mouse.js");
reload_js("scripts/tabs/jquery.ui.sortable.js");
reload_js("scripts/tabs/jquery.ui.tabs.js");
reload_js("scripts/chat_room.js");
</script>
And I use this Javascript file to refresh my css's. One that I found here.
<script src="../../global/scripts/css_refresh.js" type="text/javascript"></script>
I'm scared that these methods cause unnecessary overhead, because they run every time a page is loaded.
Could one of you experts please tell me if this is the most efficient method for updating? Or perhaps recommend a better method to keep these files up to date?
Simplest way to fix this is to add an identifier to the script/style-files. Just add something like ?version=12 (and update the number for each release) then the browser will fetch the newest file. You can also use some sort of server-side date-option after the ?of course, to force a new fetch every day or similar.

jQuery undefined only in IE9 [duplicate]

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();

Using the <script async> tag with Angular.js

Ilya Grigorik recommends the use of the <script async> tag where possible.
Is there a clean, preferred way to load an Angular.js app using the tag, without using tools like require.js or the $script.js tool recommended by the angular-seed?
The obvious issue is execution order. e.g. preventing:
Uncaught ReferenceError: angular is not defined
https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/
If there's something useful you can show without angular (e.g., a pre-generated content using a headless browser) AND nothing but your script depends on it1, then there can be a solution:
load angular.js using async
encapsulate you code in a function body
add a loop checking if angular is defined
and sleeping for a few milliseconds if not
otherwise, executing your code and breaking out of the loop
This sort of busy waiting is ugly, but I can't see how to get called back when the loading finishes. It may work or not, I haven't tried it yet.
It's quite possible that I'm doing nothing but a primitive version of what the frameworks do.
If you don't need it to work in all browsers, then there's the defer tag. To me, defer looks like async done right.
1 So I guess, users of angular-route.js or alike are out of luck. This is just a guess as I've never tried to load the two out of order.
According to this answer you might want to try to use defer instead of async, which leads to the browser to respect the loading order. E.g.:
<script src="scripts/vendor-including-angular.js" defer></script>
<script src="scripts/your-app.js" defer></script>
You may want to merge all dependent JS files into one before using async.
Use Grunt, Gulp, Broccoli or another task runner for this.
If the script is modular and does not rely on any scripts then use async.
Source: Frontend performance tips for web developers.
DON'T USE async attribute with Angular.js script tag.
It seems that using async attribute is harmful. Without it, expressions are evaluated on DOMContentLoaded event, but with the async attribute, there are evaluated on window load event, that is much later. Tested for Angular.js 1.0 and 1.4 in latest version of Firefox, Chrome and IE11.

Categories