Why google is using the term "Render-Blocking JavaScript"? - javascript

See:
https://developers.google.com/speed/docs/insights/BlockingJS
Google is talking there about "Render-Blocking JavaScript", but in my opinion that term is incorrect, confusing and misleading. It almost looks like "Google" is also not understanding it?
This point is that Javascript execution is always pausing / blocking rendering AND also always pausing / blocking the "HTML parser" (at least in Chrome and Firefox). It's even blocking it in case of an external js file, in combination with an async script tag!
So talking about removing "render-blocking Javascript" by for example using async, implies that there is also non blocking Javascript or that "async Javascript execution" is not blocking rendering, but that's not true!
The correct term would be: "Render-Blocking Download(s)". With async you will avoid that: downloading the js file, will not pause / block rendering. But the execution will still block rendering.
One more example which confirms it looks like Google is not "understanding" it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
Some HTML line and this is above the fold
<script>
// Synchronous delay of 5 seconds
var timeWhile = new Date().getTime();
while( new Date().getTime() - timeWhile < 5000 );
</script>
</body>
</html>
I tested it in Firefox and Chrome and they are showing (rendering): "Some HTML line and this is above the fold" after 5 seconds and not within 5 seconds!!!! It looks like Google is thinking that in a case like that, the Javascript will not block rendering, but as expected from theory, it will block. Before the js execution will start, all the html is already in the DOM (execept end body / html tag), but rendering is not done yet and will be paused. So if Google would be really aware of this, then Chrome would first finish rendering before starting with the execution of javascript.
If you take the example above and you're using:
<script src="delay.js" async></script>
or
<script src="delay.js"></script>
instead of internal javascript. Then it can also give the same results as the example above. For example:
If the preloader (scanning for files to already download) already would have downloaded "delay.js", before the "HTML parser" is coming at the Javascript part.
Usually external files from Google, Facebook et cetera are already stored in the cache, so there is no download and they just take the file from cache.
In cases like that (and also with async), the result will be the same as the example above (at least in pretty a lot of cases). Because if there is no extra download time, the "Javascript execution" will / can already start, before the preceding html finished rendering.
So in a case like that you could even consider to put "no-cache" / "no-store" on delay.js (or even extra delay), to make your page render more fast. By forcing a download (or extra delay) you will give the browser some extra time to finish rendering of the preceding html, before executing the render blocking Javascript.
So i really don't understand why Google (and others) are using the term "Render-Blocking JavaScript", while from theory and from "real life" examples it looks like it's the wrong term and wrong thinking. I see noone talking about this on the internet, so i don't understand. I know i am f**king intelligent (j/k), but it looks kind of weird to me, to be the only one with the thoughts above.

I work with developers on Chrome, Firefox, Safari and Edge, and I can assure the people working on these aspects of the browser understand the difference between async/defer and neither. You might find others will react more politely to your questions if you ask them politely.
Here's an image from the HTML spec on script loading and execution:
This shows that the blocking happens during fetch if a classic script has neither async or defer. It also shows that execution will always block parsing, or certainly the observable effects of parsing. This is because the DOM and JS run on the same thread.
I tested it in Firefox and Chrome and they are showing (rendering): "Some HTML line and this is above the fold" after 5 seconds and not within 5 seconds!!!!
Browsers may render the line above, but nothing below. Whether the above line renders depends on the timing of the event loop in regards to the screen refresh.
It looks like Google is thinking that in a case like that, the Javascript will not block rendering
I'm struggling to find a reference to this. You linked to my article in an email you sent me, which specifically talks about rendering being blocked during fetching.
In cases like that (and also with async), the result will be the same
That isn't guaranteed by the spec. You're relying on retrieval from the cache being instant, which may not be the case.
in a case like that you could even consider to put "no-cache" / "no-store" on delay.js (or even extra delay), to make your page render more fast. By forcing a download (or extra delay) you will give the browser some extra time to finish rendering of the preceding html, before executing the render blocking Javascript.
Why not use defer in this case? It achieves the same without the bandwidth penalty and unpredictability.

Maarten B, I did test you code and you are correct indeed. Whether you use async, defer or whatever, the lines above the inline JavaScript are not beeing rendered. The information in the documentation of Google is therefore incorrect.

Related

Difference in performance and memory footprint between referencing a Javascript using src or directly injecting it in the HEAD

What are the differences in performance and memory footprint , if any, in these different approaches:
1. Using Src
<script type='text/javascript" src="1MBOfjavascript.js"></script>
2. Directly injecting in the Head
$('head').append("<script type='text/javascript'>1MBOfJavascriptCode</script>");
I'm interested because we are developing a Cordova App where we use the second method to Inject to the DOM a previously downloaded Javascript bundle read from the HTML Local Storage.
Given that the script will probably grow in size, I'd like to know if with the second method I could incur in some memory issues or other DOM problem.
I believe the overhead in such cases should be insignificant as the main processing/memory consumption is based on how the actual script works. Ie the memory used by file would be the total size of the script which is what 1MB at max? However during execution the same script can use up 100MB easily.
Anyways , coming to the point.
Plain text inclusion would be better if it has to be included in all cases as it skips a script execution and also does not cause re-rendering by browser after the append.
Append option should be used in cases where you only need the script under specific conditions on client side and do not load it un-necessarily.
The browser goes through all elements before to render the page so I would imagine it is exactly the same, if anything if you had scripts after the page is downloaded chances are that you will get errors of the type "call to undefined functions" if you call onto a function that you have added after the load.
My advise would be add them at load using src but keep things tidy.
Javascript impact a lot depending upon how and where you are loading your file, there are many ways to load a file or code.
First method you mentioned is an conventional way to load javascipt file that is load file using src and usually its loaded before closing </head> tag but now a days it is in trend to load file befor your </body> tag. it speeds up application load and prepare DOM faster.
second method is not obviously a good way to load javascript at first as there can be some code that should be working only after your DOM is ready and as here you are loading your javscript with javascript/jquery append which depends upon your jquery file loading which will delay your code execution. and there might be possible that some of your code will not have desired output (depending upon how you have called functions and how much they are dependent upon DOM ready )
I would prefer to load a javascript file with first method and at the bottom of the page/app if possible.
asyncrounous loading can also be tried.
i think because browser behavior after retrieving response from any web server
will try to parse all the elements first for building the DOm, after the DOM are ready then your script would be executed, based on this it is obvious its the main
reasons is which is the first
will be executed first than injecting it.
About the second method
i think javascript engine in each browser can handle that thing easily and withouth any problem. the engine does not care about the size actually it only about how long the script will be loaded and then executed. what will be the issue is when you try injecting any elements into DOM is when you try to do it in loop there might be a memory problem.
when you say big javascript files yeah we should think about the memory. but
about the method you previously said its just about which are executed first.
thats my opinion

Should CSS always precede JavaScript?

In countless places online I have seen the recommendation to include CSS prior to JavaScript. The reasoning is generally, of this form:
When it comes to ordering your CSS and JavaScript, you want your CSS
to come first. The reason is that the rendering thread has all the
style information it needs to render the page. If the JavaScript
includes come first, the JavaScript engine has to parse it all before
continuing on to the next set of resources. This means the rendering
thread can't completely show the page, since it doesn't have all the
styles it needs.
My actual testing reveals something quite different:
My test harness
I use the following Ruby script to generate specific delays for various resources:
require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'date'
class Handler < EventMachine::Connection
include EventMachine::HttpServer
def process_http_request
resp = EventMachine::DelegatedHttpResponse.new( self )
return unless #http_query_string
path = #http_path_info
array = #http_query_string.split("&").map{|s| s.split("=")}.flatten
parsed = Hash[*array]
delay = parsed["delay"].to_i / 1000.0
jsdelay = parsed["jsdelay"].to_i
delay = 5 if (delay > 5)
jsdelay = 5000 if (jsdelay > 5000)
delay = 0 if (delay < 0)
jsdelay = 0 if (jsdelay < 0)
# Block which fulfills the request
operation = proc do
sleep delay
if path.match(/.js$/)
resp.status = 200
resp.headers["Content-Type"] = "text/javascript"
resp.content = "(function(){
var start = new Date();
while(new Date() - start < #{jsdelay}){}
})();"
end
if path.match(/.css$/)
resp.status = 200
resp.headers["Content-Type"] = "text/css"
resp.content = "body {font-size: 50px;}"
end
end
# Callback block to execute once the request is fulfilled
callback = proc do |res|
resp.send_response
end
# Let the thread pool (20 Ruby threads) handle request
EM.defer(operation, callback)
end
end
EventMachine::run {
EventMachine::start_server("0.0.0.0", 8081, Handler)
puts "Listening..."
}
The above mini server allows me to set arbitrary delays for JavaScript files (both server and client) and arbitrary CSS delays. For example, http://10.0.0.50:8081/test.css?delay=500 gives me a 500 ms delay transferring the CSS.
I use the following page to test.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type='text/javascript'>
var startTime = new Date();
</script>
<link href="http://10.0.0.50:8081/test.css?delay=500" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://10.0.0.50:8081/test2.js?delay=400&jsdelay=1000"></script>
</head>
<body>
<p>
Elapsed time is:
<script type='text/javascript'>
document.write(new Date() - startTime);
</script>
</p>
</body>
</html>
When I include the CSS first, the page takes 1.5 seconds to render:
When I include the JavaScript first, the page takes 1.4 seconds to render:
I get similar results in Chrome, Firefox and Internet Explorer. In Opera, however, the ordering simply does not matter.
What appears to be happening is that the JavaScript interpreter refuses to start until all the CSS is downloaded. So, it seems that having JavaScript includes first is more efficient as the JavaScript thread gets more run time.
Am I missing something? Is the recommendation to place CSS includes prior to JavaScript includes not correct?
It is clear that we could add async or use setTimeout to free up the render thread or put the JavaScript code in the footer, or use a JavaScript loader. The point here is about ordering of essential JavaScript bits and CSS bits in the head.
This is a very interesting question. I've always put my CSS <link href="...">s before my JavaScript <script src="...">s because "I read one time that it's better." So, you're right; it's high time we do some actual research!
I set up my own test harness in Node.js (code below). Basically, I:
Made sure there was no HTTP caching so the browser would have to do a full download each time a page is loaded.
To simulate reality, I included jQuery and the H5BP CSS (so there's a decent amount of script/CSS to parse)
Set up two pages - one with CSS before script, one with CSS after script.
Recorded how long it took for the external script in the <head> to execute
Recorded how long it took for the inline script in the <body> to execute, which is analogous to DOMReady.
Delayed sending CSS and/or script to the browser by 500 ms.
Ran the test 20 times in the three major browsers.
Results
First, with the CSS file delayed by 500 ms (the unit is milliseconds):
Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 583 36 | 559 42 | 565 49
St Dev | 15 12 | 9 7 | 13 6
------------|--------------|--------------|------------
Body Exec | | |
Average | 584 521 | 559 513 | 565 519
St Dev | 15 9 | 9 5 | 13 7
Next, I set jQuery to delay by 500 ms instead of the CSS:
Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 597 556 | 562 559 | 564 564
St Dev | 14 12 | 11 7 | 8 8
------------|--------------|--------------|------------
Body Exec | | |
Average | 598 557 | 563 560 | 564 565
St Dev | 14 12 | 10 7 | 8 8
Finally, I set both jQuery and the CSS to delay by 500 ms:
Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 620 560 | 577 577 | 571 567
St Dev | 16 11 | 19 9 | 9 10
------------|--------------|--------------|------------
Body Exec | | |
Average | 623 561 | 578 580 | 571 568
St Dev | 18 11 | 19 9 | 9 10
Conclusions
First, it's important to note that I'm operating under the assumption that you have scripts located in the <head> of your document (as opposed to the end of the <body>). There are various arguments regarding why you might link to your scripts in the <head> versus the end of the document, but that's outside the scope of this answer. This is strictly about whether <script>s should go before <link>s in the <head>.
In modern DESKTOP browsers, it looks like linking to CSS first never provides a performance gain. Putting CSS after script gets you a trivial amount of gain when both CSS and script are delayed, but gives you large gains when CSS is delayed. (Shown by the last columns in the first set of results.)
Given that linking to CSS last does not seem to hurt performance but can provide gains under certain circumstances, you should link to external style sheets after you link to external scripts only on desktop browsers if the performance of old browsers is not a concern. Read on for the mobile situation.
Why?
Historically, when a browser encountered a <script> tag pointing to an external resource, the browser would stop parsing the HTML, retrieve the script, execute it, then continue parsing the HTML. In contrast, if the browser encountered a <link> for an external style sheet, it would continue parsing the HTML while it fetched the CSS file (in parallel).
Hence, the widely-repeated advice to put style sheets first – they would download first, and the first script to download could be loaded in parallel.
However, modern browsers (including all of the browsers I tested with above) have implemented speculative parsing, where the browser "looks ahead" in the HTML and begins downloading resources before scripts download and execute.
In old browsers without speculative parsing, putting scripts first will affect performance since they will not download in parallel.
Browser Support
Speculative parsing was first implemented in: (along with the percentage of worldwide desktop browser users using this version or greater as of Jan 2012)
Chrome 1 (WebKit 525) (100%)
Internet Explorer 8 (75%)
Firefox 3.5 (96%)
Safari 4 (99%)
Opera 11.60 (85%)
In total, roughly 85% of desktop browsers in use today support speculative loading. Putting scripts before CSS will have a performance penalty on 15% of users globally; your mileage may vary based on your site's specific audience. (And remember that number is shrinking.)
On mobile browsers, it's a little harder to get definitive numbers simply due to how heterogeneous the mobile browser and OS landscape is. Since speculative rendering was implemented in WebKit 525 (released Mar 2008), and just about every worthwhile mobile browser is based on WebKit, we can conclude that "most" mobile browsers should support it. According to quirksmode, iOS 2.2/Android 1.0 use WebKit 525. I have no idea what Windows Phone looks like.
However, I ran the test on my Android 4 device, and while I saw numbers similar to the desktop results, I hooked it up to the fantastic new remote debugger in Chrome for Android, and Network tab showed that the browser was actually waiting to download the CSS until the JavaScript code completely loaded – in other words, even the newest version of WebKit for Android does not appear to support speculative parsing. I suspect it might be turned off due to the CPU, memory, and/or network constraints inherent to mobile devices.
Code
Forgive the sloppiness – this was Q&D.
File app.js
var express = require('express')
, app = express.createServer()
, fs = require('fs');
app.listen(90);
var file={};
fs.readdirSync('.').forEach(function(f) {
console.log(f)
file[f] = fs.readFileSync(f);
if (f != 'jquery.js' && f != 'style.css') app.get('/' + f, function(req,res) {
res.contentType(f);
res.send(file[f]);
});
});
app.get('/jquery.js', function(req,res) {
setTimeout(function() {
res.contentType('text/javascript');
res.send(file['jquery.js']);
}, 500);
});
app.get('/style.css', function(req,res) {
setTimeout(function() {
res.contentType('text/css');
res.send(file['style.css']);
}, 500);
});
var headresults={
css: [],
js: []
}, bodyresults={
css: [],
js: []
}
app.post('/result/:type/:time/:exec', function(req,res) {
headresults[req.params.type].push(parseInt(req.params.time, 10));
bodyresults[req.params.type].push(parseInt(req.params.exec, 10));
res.end();
});
app.get('/result/:type', function(req,res) {
var o = '';
headresults[req.params.type].forEach(function(i) {
o+='\n' + i;
});
o+='\n';
bodyresults[req.params.type].forEach(function(i) {
o+='\n' + i;
});
res.send(o);
});
File css.html
<!DOCTYPE html>
<html>
<head>
<title>CSS first</title>
<script>var start = Date.now();</script>
<link rel="stylesheet" href="style.css">
<script src="jquery.js"></script>
<script src="test.js"></script>
</head>
<body>
<script>document.write(jsload - start);bodyexec=Date.now()</script>
</body>
</html>
File js.html
<!DOCTYPE html>
<html>
<head>
<title>CSS first</title>
<script>var start = Date.now();</script>
<script src="jquery.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script>document.write(jsload - start);bodyexec=Date.now()</script>
</body>
</html>
File test.js
var jsload = Date.now();
$(function() {
$.post('/result' + location.pathname.replace('.html','') + '/' + (jsload - start) + '/' + (bodyexec - start));
});
jQuery was jquery-1.7.1.min.js
There are two main reasons to put CSS before JavaScript.
Old browsers (Internet Explorer 6-7, Firefox 2, etc.) would block all subsequent downloads when they started downloading a script. So if you have a.js followed by b.css they get downloaded sequentially: first a then b. If you have b.css followed by a.js they get downloaded in parallel so the page loads more quickly.
Nothing is rendered until all stylesheets are downloaded - this is true in all browsers. Scripts are different - they block rendering of all DOM elements that are below the script tag in the page. If you put your scripts in the HEAD then it means the entire page is blocked from rendering until all stylesheets and all scripts are downloaded. While it makes sense to block all rendering for stylesheets (so you get the correct styling the first time and avoid the flash of unstyled content FOUC), it doesn't make sense to block rendering of the entire page for scripts. Often scripts don't affect any DOM elements or just a portion of DOM elements. It's best to load scripts as low in the page as possible, or even better load them asynchronously.
It's fun to create examples with Cuzillion. For example, this page has a script in the HEAD so the entire page is blank until it's done downloading. However, if we move the script to the end of the BODY block the page header renders since those DOM elements occur above the SCRIPT tag, as you can see on this page.
I would not emphasize too much on the results that you have got. I believe that it is subjective, but I have a reason to explain you that it is better to put in CSS before JavaScript.
During the loading of your website, there are two scenarios that you would see:
Case 1: white screen → unstyled website → styled website → interaction → styled and interactive website
Case 2: white screen → unstyled website → interaction → styled website → styled and interactive website
I honestly can't imagine anyone choosing Case 2. This would mean that visitors using slow Internet connections will be faced with an unstyled website, that allows them to interact with it using JavaScript (since that is already loaded). Furthermore, the amount of time spend looking at an unstyled website would be maximized this way. Why would anyone want that?
It also works better, as jQuery states:
"When using scripts that rely on the value of CSS style properties,
it's important to reference external stylesheets or embed style
elements before referencing the scripts".
When the files are loaded in the wrong order (first JavaScript, then CSS), any JavaScript code relying on properties set in CSS files (for example, the width or height of a div) won't be loaded correctly. It seems that with the wrong loading order, the correct properties are 'sometimes' known to JavaScript (perhaps this is caused by a race condition?). This effect seems bigger or smaller depending on the browser used.
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
I include CSS files before JavaScript for a different reason.
If my JavaScript code needs to do dynamic sizing of some page element (for those corner cases where CSS is really a main in the back) then loading the CSS after the JS is russing can lead to race conditions, where the element is resized before CSS styles are applied and thus looks weird when the styles finally kick in. If I load the CSS beforehand I can guarantee that things run in the intended order and that the final layout is what I want it to be.
Is the recommendation to include CSS before JavaScript invalid?
Not if you treat it as simply a recommendation. But if your treat it as a hard and fast rule?, yes, it is invalid.
From Window: DOMContentLoaded event:
Stylesheet loads block script execution, so if you have a <script>
after a <link rel="stylesheet" ...> the page will not finish parsing
and DOMContentLoaded will not fire - until the stylesheet is loaded.
It appears that you need to know what each script relies on and make sure that execution of the script is delayed until after the right completion event. If the script relies only on the DOM, it can resume in ondomready/domcontentloaded. If it relies on images to be loaded or style sheets to be applied, then if I read the above reference correctly, that code must be deferred until the onload event.
I don't think that one sock size fits all, even though that is the way they are sold and I know that one shoe size does not fit all. I don't think that there is a definitive answer to which to load first, styles or script. It is more a case by case decision of what must be loaded in what order and what can be deferred until later as not being on the "critical path".
To speak to the observer that commented that it is better to delay the users ability to interact until the sheet is pretty. There are many of you out there and you annoy your counterparts that feel the opposite. They came to a site to accomplish a purpose and delays to their ability to interact with a site while waiting for things that don't matter to finish loading are very frustrating. I am not saying that you are wrong, only that you should be aware that there is another faction that exists that does not share your priority.
This question particularly applies to all of the ads being placed on web sites. I would love it if site authors rendered just placeholder divs for the ad content and made sure that their site was loaded and interactive before injecting the ads in an onload event. Even then I would like to see the ads loaded serially instead of all at once because they impact my ability to even scroll the site content while the bloated ads are loading. But that is just one person's point of view.
Know your users and what they value.
Know your users and what browsing environment they use.
Know what each file does, and what its prerequisites are. Making everything work will take precedence over both speed and pretty.
Use tools that show you the network time line when developing.
Test in each of the environments that your users use. It may be needed to dynamically (server side, when creating the page) alter the order of loading based on the users environment.
When in doubt, alter the order and measure again.
It is possible that intermixing styles and scripts in the load order will be optimal; not all of one then all of the other.
Experiment not just what order to load the files but where. head? In body? After body? DOM Ready/Loaded? Loaded?
Consider async and defer options when appropriate to reduce the net delay the user will experience before being able to interact with the page. Test to determine if they help or hurt.
There will always be trade-offs to consider when evaluating the optimal load order. Pretty vs. responsive being just one.
Updated 2017-12-16
I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.
Synchronous <script src...> will block downloading of the resources
below it until it is downloaded and executed
This is no longer true. Have a look at the waterfall generated by Chrome 63:
<head>
<script src="//alias-0.redacted.com/payload.php?type=js&delay=333&rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&delay=333&rand=3"></script>
</head>
<link rel=stylesheet> will not block download and execution of
scripts below it
This is incorrect. The style sheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:
<link href="//alias-0.redacted.com/payload.php?type=css&delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&block=1000"></script>
Keeping the above in mind, the results in OP can be explained as follows:
CSS First:
CSS Download 500 ms:<------------------------------------------------>
JS Download 400 ms:<-------------------------------------->
JS Execution 1000 ms: <-------------------------------------------------------------------------------------------------->
DOM Ready #1500 ms: ◆
JavaScript First:
JS Download 400 ms:<-------------------------------------->
CSS Download 500 ms:<------------------------------------------------>
JS Execution 1000 ms: <-------------------------------------------------------------------------------------------------->
DOM Ready #1400 ms: ◆
The 2020 answer: it probably doesn't matter
The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.
I included a more detailed writeup on my blog
I'm not exactly sure how your testing 'render' time as your using JavaScript. However, consider this:
One page on your site is 50 kB which is not unreasonable. The user is on the East Coast while your server is on the west. MTU is definitely not 10k so there will be a few trips back and forth. It may take 1/2 a second to receive your page and style sheets. Typically (for me) JavaScript (via jQuery plugin and such) are much more than CSS. There’s also what happens when your Internet connection chokes up midway on the page, but let’s ignore that (it happens to me occasionally and I believe the CSS renders, but I am not 100% sure).
Since CSS is in head, there may be additional connections to get it which means it potentially can finish before the page does. Anyway, during the type the remainder of the page takes and the JavaScript files (which is many more bytes) the page is unstyled which makes the site/connection appear slow.
Even if the JavaScript interpreter refuses to start until the CSS is done, the time taken to download the JavaScript code, especially when far from the server, is cutting into CSS time, which will make the site look not pretty.
It’s a small optimization, but that’s the reason for it.
Here is a summary of all the previous major answers:
For modern browsers, put the CSS content wherever you like it. They would analyze your HTML file (which they call speculative parsing) and start downloading CSS in parallel with HTML parsing.
For old browsers, keep putting the CSS on top (if you don't want to show a naked, but interactive page first).
For all browsers, put the JavaScript content as far down on the page as possible, since it will halt parsing of your HTML. Preferably, download it asynchronously (i.e., an Ajax call).
There are also some experimental results for a particular case which claims putting JavaScript first (as opposed to traditional wisdom of putting CSS first) gives better performance, but there isn't any logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JavaScript is invalid for the modern browsers. Put CSS wherever you like, and put JavaScript towards the end, as possible.
Steve Souders has already given a definitive answer, but...
I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.
Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.
How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...
The first file downloaded should get the connection used for the HTML page, and the second file downloaded will get the new connection. (Flushing the <head> early alters that dynamic, but it's not being done here.)
In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away. In older browsers this isn't true, and the second connection will have the overhead of being opened.
Quite how/if this affects the outcome of the tests I'm not sure.
I think this won’t be true for all the cases. Because the CSS content will download parallel, but JavaScript code can’t. Consider for the same case:
Instead of having a single piece of CSS content, take two or three CSS files and try it out these ways,
CSS..CSS..JavaScript
CSS..JavaScript..CSS
JavaScript..CSS..CSS
I'm sure CSS..CSS..JavaScript will give a better result than all others.
We have to keep in mind that new browsers have worked on their JavaScript engines, their parsers and so on, optimizing common code and markup problems in a way that problems experienced in ancient browsers such Internet Explorer 8 or before are no longer relevant, not only with regards to markup but also to use of JavaScript variables, element selectors, etc.
I can see in the not-so-distant future a situation where technology has reached a point where performance is not really an issue any more.
Personally, I would not place too much emphasis on such "folk wisdom." What may have been true in the past might well not be true now. I would assume that all of the operations relating to a web-page's interpretation and rendering are fully asynchronous ("fetching" something and "acting upon it" are two entirely different things that might be being handled by different threads, etc.), and in any case entirely beyond your control or your concern.
I'd put CSS references in the "head" portion of the document, along with any references to external scripts. (Some scripts may demand to be placed in the body, and if so, oblige them.)
Beyond that ... if you observe that "this seems to be faster/slower than that, on this/that browser," treat this observation as an interesting but irrelevant curiosity and don't let it influence your design decisions. Too many things change too fast. (Anyone want to lay any bets on how many minutes it will be before the Firefox team comes out with yet another interim-release of their product? Yup, me neither.)

Is there a known workaround for IE9's execution order of injected script tags?

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

Implications of multiple <script> tags in HTML

I have read that it is not recommended to instantiate jQuery multiple times in your HTML. This makes perfect sense to me, but:
Isn't Javascript single-threaded anyway? And leaving jQuery behind, how does the browser execute these multiple script tags? In parallel or one after another?
Thanks, Philip
Simple answer:
In a simple scenario (tags are part of original HTML text), the browser definitely executes them one after another.
Detailed discussion with different caveats
JavaScript isn't necessarily single-threaded (it depends on the implementation of your JavaScript engine, e.g. see Web Workers).
BUT, the individual <script> tags are executed sequentially.
For reference, please see JavaScript: The Definitive Guide. Quoting Chapter "12.3. Execution of JavaScript Programs":
JavaScript statements that appear between and tags are executed in order of appearance; when more than one script appears in a file, the scripts are executed in the order in which they appear. If a script calls document.write( ), any text passed to that method is inserted into the document immediately after the closing tag and is parsed by the HTML parser when the script finishes running. The same rules apply to scripts included from separate files with the src attribute.
Please note that the above is only true of "straight up" execution of code in tags. The order can, however, be affected by:
setTimeout() calls (duh)
defer attribute
Dynamic attachement of the <script> tags - see the last section of this answer.
As a caveat, please note that JavaScript code loaded externally via <script src="xxxx" /> would still be executed sequentially, BUT, it is quite possible that the browser would DOWNLOAD the code in parallel - depends on browser implementation (but still schedule the execution of downloaded code snippets in correct order).
This caveat is important in case you want to have some weird hack whereas the URL for the JavaScript source is actually a CGI script which does something and you try to depend on the correct order of downloads for the logic in the script.
Again, it would have no bearing on your browser JS engine's execution order of those script pieces.
However, a far more important caveat is that if you actually attach the <script> tags with external sources dynamically (e.g. via appendChild() call), according to this SO post, as well as the MSDN blog the post was based on, non-IE browsers do NOT guarantee the order of execution! It will depend on which tag's code finished downloading first!
The fewer calls you make that instantiate a jQuery object, the less overhead you have -- but even if you are designing for old browsers running on 2nd generation hardware be wary of micro-optimizations. Profile your application and fix the parts that actually are the bottlenecks.
As for the way browsers handle multiple script tags -- it varies from browser to browser, from version to version, and sometimes even from operating system to operating system. All browsers execute each script tag in document order:
<script src="scripts/some_script.js"></script> <!-- Executed 1st -->
<script src="scripts/some_other_script.js"></script> <!-- Executed 2nd -->
<script>
// Some JavaScript
</script> <!-- Executed 3rd -->
<script>
// Some More JavaScript
</script> <!-- Executed 4th -->
However, other behaviors are not defined and there is variation. For example, Opera (at least on Windows XP for version 10.6) ran each script tag in its own context -- so local variables in the 3rd script block would be out of scope if referred to in the 4th script block.
<script>
var i = 42;
</script>
<script>
alert(i);
// Alerts "undefined" in Opera, but 42 in Firefox.
</script>
The browser executes JavaScript sequentially (the same is true for jQuery since jQuery is just JavaScript).
As for having multiple script tags in HTML, there's no reason why this would be a problem. As Nabab asked, I would be interested in seeing your source for that.
Doesn't the browser compile all the javascript anyway into one "file" during processing. For example, if you had multiple $(document).ready() calls across multiple files, when the browser pre-processes the page, it essentially condenses everything down for execution - and runs it sequentially in the order it was 'seen'.
Yes, we can write any number of tags inside tag. And browser access them in sequential order.
<html>
<body>
<!-- here your code-->
<script></script>
<script></script>
<script></script>
.
.
.
<script></script>
</body>
</html>

Is Javascript parsed/interpreted on load? (IE)

I Know, for instance, that when Chrome downloads a Javascript file, it is interpreted and JITed.
My question is, when IE6,7,8, first download a Javascript file, is the entire thing parsed and interpreted?
My understanding was that only top level function signatures and anything executed in the global scope was parsed on load. And then function bodies and the rest were parsed on execution.
If they are fully parsed on load, what do you think the time savings would be on deferring the function bodies to be downloaded and parsed later?
They are fully parsed on load. (IE has to parse the script to know where each function body ends, of course.) In the open-source implementations, every function is compiled to bytecode or even to machine code at the same time, and I imagine IE works the same way.
If you have a page that's actually loading too slowly, and you can defer loading 100K of script that you're probably not going to use, it might help your load times. Or not—see the update below.
(Trivia: JS benchmarks like Sunspider generally do not measure the time it takes to parse and compile the code.)
UPDATE – Since I posted this answer, things have changed! Implementations still parse each script on load at least enough to detect any SyntaxErrors, as required by the standard. But they sometimes defer compiling functions until they are first called.
Because defining a function is actually an operation, yes, your entire javascript file is parsed, and all of the top-level operations are interpreted. The code inside of your functions is not actually executed until it's called, but it is parsed.
for example:
var i=0;
var print = function( a ) {
document.getElementById( 'foo' ).innerHtml = a;
}
Everything gets parsed in the above example, and lines 1 and 2 get executed. However, line 3 doesn't get executed until it's called.
There are little "perceptual games" you can play with your users, like putting the script tags at the bottom of the HTML instead of at the top, so that the browser will render the top of the page before it receives the instructions to download and parse the javascript. You could probably also push your function definitions into a document.onload function, so that they don't get executed until after the whole page is loaded and in memory. However, this could cause a "flash of unstyled content" if your javascript is applying visual styles to things (such as jQuery UI stuff).
Yes, on all browsers the downloading of the resource blocks everything else on the page (CSS downloading, other JS downloading, rendering) if done with a <script> tag.
If you're loading all the javascript at the beginning or throughout your page you will see hiccups as a request is about 50ms and the parsing for a library file or something similar could be more than 100ms. 100ms is used as the standard for which anything greater will be noticed as "lag" by the user.
The time savings may be negligible, but the slight loss of user experience if there are pauses when your page is loading may be significant depending on your situation.
See LABjs' site for a lot of articles and great explanations on the benefits of deferring loading and parsing.
What do you mean by "downloads"? When it's included with tag, or when it's downloaded through XMLHttpRequest?
If you mean the inclusion by script, then IE interpret all js files at once. Otherwise you will be not able to call functions in that file or see syntax error message.
If you mean download by XMLHttpRequest, then you have to evaluate the content of the file yourself.

Categories

Resources