I have jQuery added at the bottom of the page. However, when I run my site on pagespeed insights (Mobile), I get the error:
Eliminate render-blocking JavaScript and CSS in above-the-fold content
Your page has 2 blocking script resources and 1 blocking CSS
resources.
This causes a delay in rendering your page. None of the
above-the-fold content on your page could be rendered without waiting
for the following resources to load.
Try to defer or asynchronously
load blocking resources, or inline the critical portions of those
resources directly in the HTML.
See: http://learnyourbubble.com and https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Flearnyourbubble.com&tab=mobile
However, the jQuery is added at the bottom of the page. So it should be below the fold.
How can I remove this error?
It has to do with your font files.
Look at request 19 and 20 in the waterfall. These font files are considered CSS.
Notice how first paint (green vertical line) does not happen until after the font files are loaded?
Then notice the 15 JS files were loaded prrior to the font (CSS) files.
That is what Google is taking about.
Having 16 JS files is beyond excessive.
Try this: Disable JavaScript in your Browser. Notice the only change is in the menu header. Is 16 JS files worth that? I think not.
This article should explain a lot of what's happening: https://varvy.com/pagespeed/critical-render-path.html
In short though the problem is that chrome will need to load your jquery and your foundation javascript to give the initial render of the page. This is why its blocking. Just because the javascript comes after the html, does not mean that the html can be displayed yet. The rendering of the DOM is still going to block while the jquery/foundation is being loaded because chrome thinks they're vital to the page being displayed correctly. Pagespeed complains on these particularly because they're large. To alleviate this problem, there are a few things you can do, some of them detailed in the article above, some of them in here https://developers.google.com/speed/docs/insights/BlockingJS. The easiest way to tell chrome that these scripts are not vital and can be loaded "below the fold" is to add a defer or async tag to them.
I see an error calling foundation() but I will assume that you have removed it to rule it out, but it could be that this same call happens prior to load. Try to always enclose your code like:
(function($) {
// DOM ready
})(jQuery);
Have you tried loading async
Make JavaScript Asynchronous By default JavaScript blocks DOM
construction and thus delays the time to first render. To prevent
JavaScript from blocking the parser we recommend using the HTML async
attribute on external scripts. For example:
<script async src="my.js">
See Parser Blocking vs. Asynchronous JavaScript to learn more about
asynchronous scripts. Note that asynchronous scripts are not
guaranteed to execute in specified order and should not use
document.write. Scripts that depend on execution order or need to
access or modify the DOM or CSSOM of the page may need to be rewritten
to account for these constraints.
Please try with defer tag it's working for me.
<script src="filename.js" defer>
Related
I always put my script tags at the bottom of the page since it's good practice to load scripts after things like HTML/CSS and text has finished loading. I just found out about the defer attribute which basically does the same thing, that is it waits till the page has finished loading before fetching and executing scripts.
So if using the defer attribute is it necessary to physically place script tags at the bottom of the page vs inside the head tag?
I find it better for readability to keep script tags inside the head section.
<script src="script.js" defer="defer"></script>
or
<script defer="defer">
// do something
</script>
The current best practice? Use deferred scripts in order in the head, unless you need to support older browsers (IE < 10, Opera Mini, etc.) - 97.45% browser usage (ref)
Why? With defer, parsing finishes just like when we put the script at the end of the body tag, but overall the script execution finishes well before, because the script has been downloaded in parallel with the HTML parsing. This scenario will trigger the faster domInteractive event that is used for page loading speed. With async, the order in which your script will execute varies based on how fast the script is fetched, so order can be compromised. Futhermore, async scripts are executed inline and pause the parsing of the HTML.
Best practices have shifted since these answers were written, because support for the defer attribute has grown to 98% globally.
Unless you need to optimize speed for older browsers, you should put the script in the head and mark as defer. This 1) keeps all your script references in one place (more maintainable) and 2) makes the browser aware of the script sooner, which lets it start prioritizing resources earlier.
The performance difference difference should be negligible for most pages, because the browser's pre-loader probably isn't going to start downloading a deferred script until the whole document is parsed anyway. But, it shouldn't hurt, and it leaves more work for the browser, which is generally best.
First of all, the defer attribute is not supported by all browsers (and some that do support it just ignore it). Putting the script at the bottom of the page ensures that all HTML elements above it have been loaded into the DOM before the script executes. An alternative is using the onload method or using jQuery's DOM ready function.
There are different reasons why using defer in a script at the bottom of the HTML makes sense:
Not all browsers support "defer". If you put your script in the HEAD with defer and the browser does not support defer, the script blocks the parallel download of the following elements and also blocks progressive rendering for all content below the script.
If you just place the script at the bottom without defer the browser will continue to show a busy indicator until the page has finished parsing the JavaScript.
In some cases the "script at the bottom without defer" blocks progressive rendering. Tested in Google Chrome 36 and IE11 (see comment below)
It's important to know that every browser handels things like "defer" and also the busy indicators a little bit different.
Best practice should be: Put scripts at the bottom with defer.
Besides the readability aspect I only see advantages by putting scripts at the bottom with defer in comparison to "Script in Head with defer" or "Script at the bottom without defer".
While I agree with you that using 'defer' and placing scripts in header will improve readability, this attribute is still not supported by both desktop and mobile Opera (check this table for details).
I assume moving script at bottom is same as using defer or async attribute. Since defer and async are not fully legacy browser compliant, I gone with loading script at the bottom of the page.
<html>
<body>
<!-- whole block of html -->
<script type='text/javascript' src='app.js'></script>
</body>
</html>
Before doing this, I ran performance benchmark tools like GTmetrix and Google PageSpeed insight. Both shown 'render blocking' parameter as the main problem. I am bit confused now, as even after I moving these scripts at the bottom to allow content/html to load first; these tools still report render blocking as a main problem.
I did look at the other StackOverflow posts highlighting that though scripts loaded at the bottom has to have 'defer' attribute.
I have several questions:
is above true?
are these tools specifically look for 'defer' or 'async' attribute?
if I have to give a fallback w.r.t defer ( specifically for IE browsers), Do I need to use conditional statements to load non-defered scripts for IE?
Kindly suggest the best approach. Thank you in advance.
Yes, the scripts loaded even at the bottom has to have defere attribute, if it's possible in your site design and requirements
no, those tools looks for the completion of parsing
depends on the version of IE that you want to support, they will have different recommendations
Now explaining simple script, defer and async a bit, to help you understand the reasons:
Script
Simple <script> tag will stop the parsing at that point, until the script download and executes.
Async
If you will use async, then the script will not stop parsing for download as it will continue downloading in parallel with the rest of the html content. However, the script will stop the parsing for execution and only then the parsing of html will continue or complete
Defer
If you use defer, the script will not halt the parsing of html data for downloading or executing the script. So it's sort of best way to avoid any time addition to the loading time of the web page.
Please note, defer is good for reducing parsing time of html, however not always best or appropriate in every webdesign flow, so be careful when you use it.
Instead of async, maybe something like this (thanks #guest271314 for the idea)
<!DOCTYPE html>
<html>
<body>
<!-- whole block of html -->
<!-- inline scripts can't have async -->
<script type='text/javascript'>
function addScript(url){
document.open();
document.write("<scrip" + "t src = \"" + url + "\"></scr" + "ipt>");//weird quotes to avoid confusing the HTML parser
document.close();
}
//add your app.js last to ensure all libraries are loaded
addScript("jquery.js");
addScript("lodash.js");
addScript("app.js");
</script>
</body>
</html>
Is this what you wanted? You can add the async or defer attributes on the document.write call if you want.
According to HTML Spec 1.1 The script block in the html page would block the rendering of the page till the javascript file in the url is downloaded and processed.
Adding Script at the end of the page : allow the browser to continue with the page rendering and hence the user will be able to see the page rendering asap.
[Preferred] Adding defer to the script tag : promises the browser that the script does not contain any document.write or document altering code in it and hence allows it to continue rendering.
As previous thread may be useful to you
Is it necessary to put scripts at the bottom of a page when using the "defer" attribute?
Why should the scripts mentioned at last must have defer attribute?
Well, the answer is that by adding defer to last script you are actually reducing the number of critical resources that needs to be loaded before the page is painted which reduces the critical rendering path.
Yes, you are correct by the time you reach the last DOM is parsed but browser has not yet started painting the DOM and hence domContentLoadedEvent is blocked until it finishes the paint and render activity.
By adding async/defer we are telling the browser that the resource is not critical for rendering and it can be loaded and executed after dom content has loaded.
This will trigger the domContentLoaded event earlier and the sooner the domContentLoaded event fires, the sooner other application logic can begin executing.
Refer the google link below it clearly demonstrate the concept.
https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp
I have the optimisation problem — my site uses 2 (pretty large) javascript resources:
application.js (minimised jquery, jquery-ui, underscore-js and some shared scripts, 120KB total)
controller-specific file (some modules required for the page + interactions, 4KB total)
I have some scripts in the views that format/convert markup with JavaScript (dependable on both jQuery and my controller-specific JS code) so I need to wait either for $(document).ready or head.ready and it makes the part of website invisible to prevent the flash of unstyled content :(
Now my question comes: should I use head.js for it or just stick with the "before " scripts? Are there any smart ways to speed up page loading time in this case?
Update:
Here's the part of the code (see versusio.com for full code, landing page):
<html>
<head>
... usual stuff
<link (css stuff) />
<script src="head.js"></script>
<script>
// Here some global variables are set like cache keys, actual locale code etc., not dependable on jQuery or any other JS code from the JS assets
</script>
</head>
<body>
... page content
<div id="search">!-- here some code with the "display: none" style to prevent flash of unstyled content</div>
<script>
// Here is code that positions and processes some styles and adds some interactions to the #search div
Application.Position.In.Center($(#search), $(document));
</script>
... more page content
... another "display: none" div and accompanying script
... rest of the page content
<script type="text/javascript">head.js( { 'application': 'application.js' }, { 'landing': 'landing.js' } );</script>
</body>
</html>
First ask yourself this question: Do i really need all this javascript loaded when a user visits my page?
When first loading your website, you actually only need the autocomplete-functionality, the rest isn't needed on load. So you could go for a seperated approach. My advice would be the following:
Build this page without any javascript-functionality and then enhance it with javascript, get rid of the inline styles and scripts.
After you have done this, load the scripts you actually need, you can do this in the head or just before the end of the body
Use a CDN for Jquery, jquery-ui, underscore and the other libraries. If a user already loaded these libraries from another website, you have a performance bonus.
Last of all, already asynchronously load the javascript needed later on, so the user already has the scripts when he hits the compare-button.
Small tweaks:
Use a tool like ySlow or the networking graph in your favorite browser to look for any bottlenecks. It looks like gzipping is not enabled, try and do that.
Do you really need to load the facebook/google/twitter/third-party stuff in the head or could that be done when the page is loaded?
Is the server as fast as possible? It looks like it takes almost halve a second to get the HTML.
I hope i helped you out for a bit, good luck with the performance tweaking!
You could put mask layer that cover all pages with fixed style, then hide or destroy it when loading process finished. That way there's no need to hidden each content, instead it will be covered with mask div
I think, put a load scripts on the bottom of the page (as the last tags in the body). That javascript it will not block the drawing page, like now.
Saw the view source of your page.
There are some inline scripts which can block rendering. Such as this
Application.i18n = {"comparisons":{"off_ratio":
More here. http://calendar.perfplanet.com/2012/deciphering-the-critical-rendering-path/
Quick way: Moving them to the end of body tag.
Best way: They should be loaded as external scripts - with very good cache headers.
May be, you are doing that as - you have to load those messages based on user locale - You can create separate JS files for every locale during your build process - an they can be linked / loaded as external JS files with good cache headers
Another reason, why you might need inline scripts - to take note of the initial loading time. which is not necessary - as the modern browsers provide us with perfomance timings.
http://www.html5rocks.com/en/tutorials/webperformance/basics/
Moving it as an external script file - will also be good for your site security - in case, if you will be trying CSP.
http://updates.html5rocks.com/2012/11/Content-Security-Policy-1-0-is-officially-awesome.
Defer / async attributes.
ga.js is set with async attibute - but other JS files can be tried with defer attributes. Also, as a general rule of thumb, delay loading resources as far as possible,load only when it is needed.
window.onload - $.ready
Starting your script execution with $.ready is always going to be better than window.onload.
because, window.onload fires only after all the images, inner iframes gets loaded.
The following links might be useful.
https://developers.google.com/speed/
The Progressive JPEGs post in http://calendar.perfplanet.com/2012/
http://blog.chriszacharias.com/page-weight-matters
http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/
A lot of further optimisations are possible. All the best.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript on the bottom of the page?
I saw a comment in some twitter bootstrap example. It says
JavaScript placed at the end of the document so the pages load faster
Is this true?? If yes then How it works??
There are a number of advantages
There’s no need to have a check if the DOM is loaded, since by having
the scripts at the end, you know for sure it is.
A JavaScript script
file has to be loaded completely before a web browser even begins on
the next JavaScript file. The effect of this, if the JavaScript files
are included at the top of the document, is that it will be a visual
delay before the end user sees the actual page. This is completely
avoided if you include the JavaScript files at the end of the
document.
There are some limitations as well
While including the JavaScript files at the bottom helps us around the
problem of delaying the page rendering, thus giving the impression
that each page in the web site loads faster, it does have a drawback.
If the page is visible to the end user, but the JavaScript files haven’t finished loading yet, no events have been applied to the
elements yet (because everyone uses an unobtrusive approach, right?)
and the user might start clicking around and not getting the expected
results.
If you have proper fallbacks, e.g. a link element which gets content via AJAX if JavaScript is supported and the proper event has been
applied, otherwise it’s a normal link leading to another page, then
the problem isn’t that bad. Still somewhat annoying, though.
Useful Article Here
If the browser encounters a <script> tag, the HTMLRenderer will by default stop and the ECMAscript parser will do its job. The HTMLRenderer will not continue untill all the Javascript code was completely evalutated.
So, if you have many <script> tags and lots of Javascript code in your "upper" HTML code, a viewer of your site might realize a slow'ish loading process.
There are several ways to avoid this issues. The first is, as you mentioned, by just placing all the Javascript code and <script> tags at the very bottom of the <body> element. That ensures that at least all the HTML markup and Stylesheet definitions were fully loaded.
Another options are tag names for the <script> element itself. Such as async and defer will indicate to the Browser / JS Parser that this fill is not required to get loaded and evaluated immediately. For instance
<script async defer src="/foo/bar.js"></script>
The HTML Renderer will realize the tag and store it into a queue, but it will not directly stop and evaluate.
Most browsers execute JavaScript and load the page using the same thread. Hence while JavaScript is executing the page cannot load. Thus if you page contains lots of images or embedded content these assets will not start loading until the JavaScript completes execution.
This is the reason it's advised to put long running synchronous code at the end of the document, or defer it to load when the page loads or the DOM content loads. However modern browsers usually notify the user about long running blocking scripts and allow them to terminate the script if desired.
As important as placing them at the end of the page, is specifying them as async using the HTML5 async attribute. This will ensure that the parser does not stop and parse them but rather continues with the page loading flow and downloads/parses the JS in parallel.
http://davidwalsh.name/html5-async
The logic behind that concept is that since the browser renders your code on the fly, by placing all the html elements before the scripts, it could theoretically load faster than if you had the scripts first, assuming you had an astronomical amount of scripts to deal with.
In practise however no one should ever encounter a situation that would require so much script time that it would affect the load time of a website over more pressing bottlenecks as D/L bandwidth.
I've messing about with html5, I've never really had a good look at JavaScript before.
I'm referencing script file like this (not in the head)
<script src="somthing.js"></script>
However the script only seems to work if it placed below certain elements on the page.
Are there particular situations when it matters where javascript is placed?
Thanks in advance.
If the script isn't waiting for an onload or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>.
In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body> is one common practice to counter this. Some alternatives are using the window.onload event to run your code, or jQuery's $(document).ready() for example (most major libraries have some equivalent of this).
If your script is acting on an element it needs to either be placed after that element on the page or set up to execute when the page is finished loading. If the script runs before the element has been added to the DOM (which occurs when it is encountered as the browser parses the page), then the script can't find the element upon which you want it to act. Placing the script after the element ensures that the element is available for it to work on. Likewise, forcing it to run after the entire page loads makes sure that all elements are available to the script.
I'd suggest that, in so far as possible, you load your scripts right before the closing </body> tag. I would also look at using a framework, like jQuery, which makes it easy to run your scripts on page load complete and wrap the code inside it's load event.
The best practice according to Yahoo's Performance Rules is to place scripts at the bottom of the page:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
Well we'd need to know what was in your script to tell you really, but the short answer is "yes it does matter".
Scripts (essentially) execute when encountered by the browser. A classic blunder is to make a reference to a page element in a script placed earlier in the document than the element it references - when the script is executed the element doesn't exist yet!
It is generally considered appropriate to keep scripts in the head, the solution to the above problem therefore being to attach functional code to onload event handlers.
Bonus round: a much more subtle reason script placement matters is because most browsers will single-thread downloads when they encounter a script (for security reasons and because the script can modify the download requirements for example). This is one of the reasons yahoo recommends placing scripts last in your document, but it's a controversial thing to do for a subtle benefit of perception only.
YES it does.
for example, let's just say your js code is at the top. and it is interpreted before the browser is done setting up a section of the dom tree...in this case the HTML element that you are referencing, if referenced before it is available, will produce an error saying that the element is undefined.
Another reason is the user experience. If the css is at the top, when the html is displayed all looks good, but unless the js is at the bottom, you will have to wait for it to be loaded and be ready for execution before the rest is rendered; therefore, slowing down the rate at which items on the screen are rendered.
I see it a lot. Different strokes for different browsers, but just put the js at the bottom, and css at the top and you avoid having to worry about stuff like this.
It depends on what the script is designed to do. If it is using the document.write() method, then it does matter where it is on the page. If it's trying to reference elements in the DOM, it is best put in the HEAD and have those functions that access DOM elements triggered after the page is loaded.
There are a couple of scenarios where the placement is important.
Assuming you have a function call foo() in your_script.js and you call it before you include your_script.js, than it simply won't work because foo() isn't defined yet.
If the code requires a certain element to be available (for example, a lightbox script) than it is possible that loading the code before your lightbox image elements results in the lightbox not doing anything.
So basically... it depends very much on what scripts you are running. Sometimes it will matter, other times it won't.
Yahoo actually recommends putting your scripts at the bottom. The downloading of a JS file is a blocking action which means nothing else is downloading at that time (such as images/css) By putting your scripts at the bottom the user gets the html/images/css first and actually see the page faster, and your JS downloads after to add interactivity.
Having said that, as the other posts mention, your script has to wait until the dom is ready before actually doing anything to the DOM, otherwise you'll have varied behaviour depending on when the DOM is ready.
Well, here is what I think.
If you need to execute your script, before the HTML starts the render in the clients browser then it will be better to be placed in <head> section.
And if you are executing a JavaScript code which communicates with a element in some way then the script should be placed behind that element, because if the script starts ahead then it can't find its respective element to communicate with. So it is better to placed behind element.
This is not only about where the script is placed in the page, but also when the code in the script is executed.
Script tags normally goes in the head section of the page. However, that means that no elements are loaded when the code loads, and if it executed immediately you can't access any elements. The solution to that is to use the onload event of the page. Example:
<html>
<head>
<title></title>
<script>
function init() {
document.getElementById('message').innerHTML = 'Hello world!';
}
</script>
</head>
<body onload="init();">
<div id="message"></id>
</body>
</html>
Javascript libraries may have other methods of doing something similiar, like the ready event in jQuery.
You can place scripts in the page (although this is not what's recommended by the HTML standard), but if you need to access elements in the page from code that runs immediately, the script has to be loaded after the elements. Example:
<html>
<head>
<title></title>
</head>
<body>
<div id="message"></id>
<script>
document.getElementById('message').innerHTML = 'Hello world!';
</script>
</body>
</html>
Scripts may also be placed late in the page for performance reasons. You can keep that in mind and save it until you actally have any performance problems.
In simple terms : Make sure the element(s) the script accesses is loaded before the script starts executes. Ofcourse if you are unsure put it just before .
Your script likely attempts to operate on the DOM before it is ready. This should not be solved by moving it around, but rather by deferring execution with domready callbacks.
After that is sorted, you should aspire to keep script inside of head. It used to be a common practice to include scripts at the bottom of the page to avoid page- and request-blocking. In HTML5 such performance impacts no longer matter since you can take advantage of async attribute. It allows for the loading of JS files to be initiated without side-effects:
Traditional scripts block the HTML parser, preventing the rest of the page from being rendered until the script has been downloaded and run. Scripts using HTML5 async unblock the rest of the page so it can continue loading while the script is being downloaded. ^