Load javascript files asynchronously
As I have already gotten you used to, today I came back with a new tip to speed up your website when using a lot of inline or external JavaScript files on your website. As you know the browser will try to download each resources in the exact same order they were written, but what it happens with some websites that have a lot of external JavaScript files that the page will hang, or more exactly will wait for resources to load before the rest of the page is loaded. So what is the solution to this? Programmers will most likely think that the best solution is to load JavaScript files asynchronously. But how do you load all JavaScript files asynchronously in an easy way, as in you don’t need to grab each JavaScript file and then have them run only after the page is loaded, I mean doing this on-the-fly.
In my actual case the issue was with the Google+ or Google Adsense JavaScript files. The Adsense ads were really at the top of the page so on each page refresh the load was waiting for the ads to load first before the page completed, as such it would hang a little bit. The same for all other social JavaScript files that were loading.
Since two days ago I have again started to play a bit with Cloudflare CDN, I then noticed that it had a nice little option called Rocket Loaderâ„¢ (Web optimization). This does the actual asynchronously load of JavaScript files, exactly in the same order these were found on the page. The difference between enabling this option and disabling this in term of page loading time is around 2-8 seconds for my website! It also depends on each external site so we can’t be really exact.
Bellow you can see an actual test regarding this.
And after enabling Rocket Loader, see bellow result:
The difference is noticeable, as you can see, its more then half the load time reduced.
Now I should mention that this option is currently still in beta, so I already found that some issues are present, for example, I had to exclude Google+ from Rocket Loader in order for it to load on each and every page request, else on some pages will load, on others will not. To exclude certain JavaScript code from being loaded asynchronous you can use the code below:
1 |
<script data-cfasync="false" src="/javascript.js"></script> |
That’s it for today, don’t forget to share and always remember speed is important for every website!