Thursday, 10 September 2009

Loading JS Dynamically and Unobtrusively

For a while I've wanted to implement unobtrusive javascript to support Steve Souders ideas for high performance web sites. For me using unobtrusive js to load _all_ the page's js after the page has loaded is a logical extension to the philosophy of progressive enhancement; first create the HTML page, second add CSS to make it visually pleasing, and finally add the javascript to knock their socks off!! There are many more reasons to create a web page this way, but that's for another post. Others allude to this dynamic loading of js as 'progressive rendering' (obviously only if the js modifies the user interaction).

The architecture I've been creating for a general solution that can be used across different customer sites without changes, is to have a small amount of inline js in each page (preferably as the last tag before the close body tag) that loads up a small external js file when DOMContentLoaded fires that then loads all the other js the developer wants and any additional CSS files that are only used for js the enhancements to a page. In the web page the developer is able to define which js and css resources are needed by using a couple of simple api provided by the inline script; ct.resources.loadJS() and ct.resources.loadCSS().

So far I've been able to keep the inline js portion down to about 1200 bytes compacted (gzipping the HTML page should reduce the network load to about 700 bytes for the inline js), so it's pretty light. It also means that all the js and additional css is loaded _after_ the page has rendered keeping pages light and responsive from the users perspective.

Having researched into loading scripts dynamically and referring to Steve Souders lastest book, Even Faster Web Sites, I decided to base the external file's code around Steve's solutions with some modifications. However, when modifying someone else's code to address issues others have resolved when using similar techniques, as well as optimising the code and making it ready for production use from years of painful experience, always seems to take longer than first thought. Hopefully I'll have it ready in the next day or so, and then I'll be able to add Google Analytics and client libraries such as jQuery and Dojo to my pages without affecting initial page rendering responsiveness.

No comments:

Post a Comment