Friday, September 12, 2008

Place JavaScript code at bottom of page

Recently I've been placing scripts at the bottom of the page, instead if the top. However, I don't put all of them there - the key ones required by other scripts (e.g. libraries like jQuery) are still in the header. The pages can appear to load faster, and in some cases may save some (albeit not always that much) code, e.g.

....
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( function()
{
 $("a.foo").click(doSomething);
};
function doSomething()
{
 return confirm("About to visit " + this.href + ", continue?");
}
</script>
</head>
<body>
...
</body>
</html>

Can instead be:

....
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
...
<script type="text/javascript">
$("a.foo").click(doSomething);
function doSomething()
{
 return confirm("About to visit " + this.href + ", continue?");
}
</script>
</body>
</html>

In some circumstances, the script may query the CSS of an element and so the script may run before the associated stylesheet has downloaded (at least, I have experienced this in Google Chrome).

This does assume that you have not attached javascript functions inline (e.g. a onclick="doSomething()" as these would fail if the user interacts with elements before the function is available.

If you use 'DOM ready' events, then there is less benefit of doing this (as it should run when the page is ready anyway). As with any optimisations, it is always worth experimenting to reduce the time it takes for a page to be used and interacted with by visitors.

No comments: