
A few days ago I wanted to visit zen pencils webpage. You may find some inspirational quotes wrapped in pretty cartoon art. I enjoy them both. However when I opened the link in my browser it all got stuck with header shown and nothing more loading.
Page stopped loading because my browser (Opera if you do not recognize) was waiting for some external resource to load.
Fortunately I know how to overcome this issue and easily disabled scripts on this particular page. After hitting F5 the page got loaded instantly. But I’m a pro-user and I don’t think common user could figure it out. They would just simply close the tab (perhaps entire browser), got a bit angry because they didn’t see what they wanted and leave.
While nowadays keeping page load times low is very important you surely don’t want this to happen on your site.
So why page did not load properly?
For those of you who are unfamiliar with how is page processed in a browser while it’s being downloaded I will explain. Simplified version is this: Browser gets html code from the server and starts with processing. When it hits any <script>
with src
attribute (non-embedded script) or <link>
tag it will stop further page loading and waits for the linked content to download and interpret. And from there page-load block emerges.
Therefore always remember when linking external resource to your page that they might block page processing. It’s not limited only to JavaScript but applies also to stylesheet links. I mentioned JavaScript in the title just because in 99% of cases the <script>
tag is a problem.
How can I avoid that?
Do not link cross-site resources. For now they mostly are miscellaneous tools for sharing (eg. like AddThis, ShareThis services) and CDN networks. Basically it’s anything you include in your page’s source code and points to different domain. Store all the resources as local copies and provide those. Yes, it’s against CDN principle.
If you do link cross-site resource make it so it is loaded asynchronously. This is handy technique which prevents blocking the page load. You can google it easily or take a look at this article. Of course there are drawbacks. Things will get complicated if the resource is library (for example jQuery) and you want use it in your code. You must wait for the load event of the resource before you might use this library in your code.
<script> // this will load jQuery library asynchronously loadScript("http://this.is/where/jQuery.js"); // this won't work as at this time jQuery is not loaded $(function() { /* your code here... */ }); </script>
If you apply css this way than user might experience page blinking as the css loads and is applied to already displayed page.
If you do link cross-site resource and do not link it asynchronously make sure the supplier of the content is stable. Keep in mind that you will rely on the availability of the another party which you cannot influence. This rule should be applied only to large and commonly trusted CDN networks.