Page speed issue - javascript

While testing page loading time on https://developers.google.com/speed/pagespeed/insights/?url=aishwat.com it says
Eliminate render-blocking JavaScript and CSS in above-the-fold content
and lists down few javascripts (which you may look at link provided)
Now, I am using these as base scripts angular.min.js, angular-animate.min.js, angular-aria.min.js, angular-material.min.js
And they need to be loaded in this particular order (one can't load angular animate before angular)
The question is how to make them non blocking ?
I have already kept them outside head block
Source code : https://github.com/aishwat/aishwat.com/blob/develop/public/index.html
Plz have a look at source page

The PageSpeed insight site has a good documentation what you can do to prevent it.
To make your javascript non-blocking you can add the async or defer attributes to your script tags. To maintain the order it is recommended to use defer.
<script defer src="my.js">
I see your <script> tags are outside of your <body>, this is not valid HTML so I recommend putting them back at the head or somewhere in your body.

Related

Is it ever necessary for a <script> tag to go in the <head>?

I have read in the docs of some third party providers (e.g. adsense) that their script must go in the <head>.
For async scripts I'm fairly sure this is untrue since the async flag doesn't guarantee anything about when the script will be executed. But I'm curious about non-async scripts too. Does it makes sense to say that a script tag must go in the <head>?
(This is assuming that there isn't any code in the page that relies upon some script having loaded).
To be clear, my question isn't "is it a good idea", or "what are the performance benefits".
It's more like: "is it technically possible that a script could NOT work, because it isn't in the <head>?"
Thanks!
A <script></script> in the <head> tag will stop the DOM from parsing until the script has loaded. Put scripts here that need to be loaded before the DOM is parsed. Don't put any unnecessary scripts here, as it stops the DOM from parsing. That results in a slow-to-load page.
See: https://stackoverflow.com/a/24070373/47589
The MDN page on the script tag does not place any requirements on the location of a script tag. In fact it seems that the modern trend is now to put scripts at the very end of the body.
A tag can be placed anywhere in the html page, But placing in the tag will slow down the creation of DOM elements in the browser, because browser needs to get all the script tags and move to html elements,
The best practice is to keep the script tag at the bottom of DOM elements, because the visual html elements will be loaded before the script js getting load.
It mainly depends on the functionality of the script and the business logic of the page.

Using PageSpeed to eliminate render-blocking JavaScript for jQuery

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>

RequireJS script tag in <head> or at bottom of page?

Should the RequireJS script tag be located in the <head> or bottom of an HTML page?
<script data-main="resources/js/main" src="require.js"></script>
I have seen reputable sources place the RequireJS script tag in either position, but no reputable source seems to explicitly say where the ideal location is.
Arguments for placing the tag in the head would be that RequireJS could already begin loading and executing dependent scripts asynchronously while the page continues loading (though this gain may be minuscule).
Arguments for placing the tag at the bottom of the page would be that checks for the DOM being ready wouldn't be needed within modules (though not including this check may cause problems if the module is used in a third-party system that loads the script in the <head> tag).
General best practice is to always place your script at the bottom.
You may have seen people including it in the HEAD as it is not doing a big difference.
I'd recommend in the bottom, because as you'll want to build your scripts before production, you'll end up loading all your script in the head otherwise.
Note that if you're running a "single page application", then it really doesn't matter as chances are your body will be empty - or almost empty.
Put it at the bottom of the page, it's better for performance and if you're planning to manipulate the page (as expected) then you want it to load the page first anyway.
Best practice, with few exceptions, is always:
Load styles (css)
Load structure (html)
Load scripts (functionality)
I'm working on a project with a lot of templates and about 1MB of js on page load, and putting requireJS at the top of the page has it's perks. Require can start scheduling and parsing js while the rest of the html downloads. Also, we have noticed that, this allows us to 'require' css in the page before all of the html comes down.
I did find one caveat today, where script tags might execute twice if require is loaded in the page at the head/ before the script tag. I'm trying to create an example to debug.

Should use Head.js or just minified scripts before </body> with scripts in the markup?

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.

Is there a valid reason about putting JS in the head of document?

I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster).
So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example).
A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand.
Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because:
it makes sense
the script still loads after the page has finished loading
The <script> tag causes two problems:
Everything below the script won't render until the script is loaded.
All components below the script don't start downloading until the script is done.
Putting it into the <head> only really makes sense if you need to execute some JavaScript before anything gets rendered.
So placing it as low as possible in the page would result in a better user experience.
It's slightly more semantic to put it in the header, but it doesn't generally have any advantages. Sometimes it is necessary - for example, loading fonts using JavaScript (using stuff like Google Webfonts) has to be done in the header, or the page will render with the wrong font and then change, which won't look good to the user.
The important thing about the elements in the <head> section are that they are loaded, before the <body> starts to load.
This is a very efficient feature, which are used a lot (IMO).
Loading of libraries, scripts, that have to run before the DOM has loaded have to done in <head> section.
I will give you a scenario
Imagine, You needed to calculate the 30% size of the screen's total size and assign it to the element inside.
It would be foolish and wait for the element to load big, then run the script to load resize it again.

Categories