Thursday, June 25, 2009

Unobtrusive javascript

For years contributors have been posting javascript includes into their articles. The site is littered with invalid and sometimes broken includes to files that no longer exist, no longer support the architecture or are just plain old not needed anymore.

Step 1: Formulate a plan to pool all js requirements into a single updateable source.
Decision - Install a js framework library.

Step 2: Decide on an appropriate js library/architecture.
Decision - I chose jQuery, mainly because I've been using it for years and have found it to be the least bloated while offering the best degree of control with minimal lines of code. I've also tried a number of others such as Dojo and Scriptaculous, albeit in very early days. They weren't bad but suffered from being buggy or bloated or just lacking some functions I really needed (like a hover function)

Step 3: Streamline the implementation for best crawl-ability, validation and loadtimes
Decision - Remove all script from the page (unobtrusivity) and push it as far down the page as possible.

It's been common practice amongst many developers to implement all their js in the header block of pages. Traditionally this made sense because we wanted to be sure our js was readily available before we tried using it throughout the document. These days however this has become an unhealthy practice due to the bloat in js size (frameworks vs the old single use precedures). In page load terms, js hogs the download stream so nothing else on the page will download while js is coming down the pipe. This can be changed by adding defer="defer".

This is no longer appropriate however as js frameworks such as jQuery are instantiated using the document.ready protocol, so they'll only run once the document has downloaded and is displaying (usually this is the case but there's some discrepancy as to exactly when this init fires in different frameworks). So to the script tag download can be deferred by params but why bother? I've already identified that I want this to load last ... why not put it last?

Step 4: Calling the js
Decision - Install the minimum required.

There should be two inital js includes here; one to the base library and one to the document holding your library initialisation calls. Remember that we're pooling our js resources into a single point for easy updating. So our implementation methodology will be kept in an external file. I usually maintain two initialisation files, one public and one private for the CMS. In this case, I just maintain one, but the habit's still there.

<script type="text/javascript" src="js/jquery.min.js" defer="defer"></script>
<script type="text/javascript" src="js/public.js"></script>
</html>
</body>

0 comments:

Post a Comment