Positioning CSS and JS files in HTML content

Have you seen a webpage that starts to load somewhat strangely in your browser and after a couple of seconds the design changes? Or the page loading stalls for a few seconds and then loads fine?

It’s important to correctly position the external file calls to Stylesheet and JavaScript files.

Rule #1. Move all JavaScript external file calls to the bottom of your HTML code.

Rule #2. Move all StyleSheets external file calls to the top of your HTML code.

There are of course a few exceptions – for example, if you have a specific Javascript code that calls up an ad or specific block to display. In this case you will call the external file from the right place in your source. Another case can be some specific timer that can’t have a delay until the full page loads.

Always remember to have as few external include calls as possible. The more website content that can be cached, the better speeds it will provide, generally.


Comments

  1. mike503 says:

    I tried to get the best score possible using YSlow! and positioning the CSS at the top, JS at the bottom, setting appropriate gzip, expires headers, etc, etc.

    However, it seems that some Javascripts should still be at the top – jQuery, while it has a document.ready() and other options to wait until the page has finished loading, doesn’t seem to reliably perform when it’s at the bottom… especially if you have page interaction features that could be clicked/executed before the page is fully loaded.

    So for now, I include jQuery at the top and any other script(s) which have user interaction options (which at this point, is all 4 of them or whatever)

    i.e. we had a “Login” link which popped up a DHTML window layer thingy – without jQuery having the document.ready() firing yet, the link was dead (and would stay dead even after the page loaded in certain browsers) – the only way to resolve it was to reload the page and wait until it fully loaded.

    Have to make sure that you can anticipate users being impatient and code appropriately :)

Leave a Reply