Who said you shouldn’t run before you can walk? In the race to rice up web UIs with all manner of DOM manipulation magic, we are forced to be patient. Until the DOM is fully loaded and ready in the browser, we can’t walk it, creating an idle loading period in which we can’t, or don’t, run any javascript. Or can we?

Yes, most certainly we can. In this tiny whisper of time, we’ve got a great opportunity to exploit an inactive javascript engine before the serious work starts at DOM Ready. This period of time occurs before CSS styling, layout and rendering (the ‘painting’ of the UI after the previous steps). The typical model for page load in a browser is Parse/Load DOM -> Styling -> Layout -> Rendering, with javascript being allowed to execute at each step.

Of course, executing javascript before the DOM Ready ‘event’ is certainly not a new technique, but a pertinent reminder in these days where DOM manipulation is the hot topic that we don’t need the entire DOM loaded for javascript to be of use, just a little bit before the first code can be introduced in the <head />:

#Code
0001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
0002<html lang="en">
0003 <head>
0004 <title>Running...</title>
0005 <script type="text/javascript" src="/js/canhas.js"></script>
0006 </head>
0007 <body dir="ltr">

At this point, code in <script> can access and manipulate a few elements, two important ones being the Window Object and the root of the Document Object—whence the DOM descends— otherwise known as documentElement, or everyone’s favourite HTML element, <html />. On this, the very cusp of page load, we can actually do some useful startup initialisation aka bootstrapping.

Bear in mind that browsers these days reach DOM Ready very quickly, and so no matter how fiendishly inventive the code you might write to run here is, it must be compact and efficient to be downloaded and run in a manner of milliseconds. Just native javascript here, nothing fancy from your favourite framework. Expensive calculations and weighty scripts can end up having negative impact on page load times. For a start, <script /> elements block parallel downloads – that is to say that they prevent the browser from starting to download any other page assets—like images and css—until the referenced script has been downloaded, parsed and executed.

So, with this in mind, what are some simple and useful pieces of code to run?

Utilising the Window Object – frame busting!

The traditional javascript “frame buster” technique is designed to prevent sites from being enclosed in an <iframe />. For most, it’s a defensive measure against website hijacking and other similar nastiness. It’s a simple trick that requires only a reference to the parent window object.

#Code
0001if (window.self !== window.top) {
0002 window.top.location = window.self.location.href;
0003}

get this code

By making a strict comparsion—using the !== operator—of window.self (a reference to the window object itself) against window.top (a reference to the topmost window in the window hierarchy) we can ascertain whether the window of the calling page is the one it is supposed to belong to.

In a non-iframed page, top is identical to self. The topmost window in the window hierarchy is the calling page’s window and not a reference to another window outside an iframe.

In iframed pages, the condition evaluates to true, and so the parent window location is set to the calling page’s location causing the entire page to redirect directly to the calling page.

Simple, quick and handy… though not always useful. In the real world, we sometimes need to use iframes.

Utilising documentElement – enhancing accessibility

Accessibility’s not just about making your page work in a screen reader. It’s about providing a usable site for as many different types of users, in as many different environments as possible. In this code snippet, we can enhance accessibility for two types of users – javascript-enabled users and those with javascript disabled. And we can do this with CSS.

Having access to documentElement, or <html />, means we can manipulate it; notably its attributes. With a few lines of code we can modify the document’s <html /> element to enforce a global CSS class on the document… perhaps something like “canhasjs”:

#Code
0001var root = document.documentElement;
0002if (root.className.match(/\bcanhasjs\b/) === null) {
0003 root.className = (!root.className) ? 'canhasjs' : root.className + ' canhasjs';
0004}

get this code

In this code, we first check whether the class name “canhasjs” already exists using a regular expression match(). If it doesn’t, we attach it. The class name is attached under two conditions using a ternary operator for brevity – if <html /> already has a class name, we append it with a preceding space character, otherwise we just set an entirely new class name.

And voila, the page is loaded javascript aware. With this selector available it is simple to use CSS styling conditionally – enabling certain styling for javascript aware browsers, and different styling for javascript-disabled browsers.

Bringing the Two Together – accessibility and flexibility

In the first code snippet, a simple conditional informs us whether the page is iframed, while the second informs us about the availability of javascript. With a simple change, we can combine the two bits of information to initialise a page that can render in multiple states – be it iframed and javascript disabled, javascript-enabled and not iframed and so on.

#Code
0001var root = document.documentElement;
0002if (root.className.match(/\bcanhasjs\b/) === null) {
0003 root.className = (!root.className) ? 'canhasjs' : root.className + ' canhasjs';
0004}
0005 
0006if (self !== top && root.className.match(/\bcanhasiframe\b/) === null) {
0007 root.className = (!root.className) ? 'canhasiframe' : root.className + ' canhasiframe';
0008}

get this code

Produces:

#Code
0001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
0002<html lang="en" class="canhasjs canhasiframe">
0003 <head>
0004 <title>I'm in an iframe and has JS... and a flavour</title>
0005 <script type="text/javascript" src="/js/canhas.js"></script>
0006 </head>
0007 <body dir="ltr">

get this code

<iframe /> and Javascript aware CSS selector goodness!

This is a very simple, and somewhat naive, example of bootstrapping. But it provides the basic principle to build upon. A smart idea would be to perform some kind of javascript dependency handling and injection: instead of loading all your JS up front, the bootstrap code could figure out which javascript files need to be included in the page—using class names or similar attributes— and load them on demand. Or detecting window width and loading an appropriate stylesheet that would manipulate layout for smaller or larger window sizes. Lots of potential.

Comments for "Bootstrapping with Javascript"

Commenting is now closed for this article

About

beardscratchers.com is a music-focused web experiment and creative-arts journal from London, England.

Subscribe/Syndicate

Categories

Previous Entries…

Journal content and design are © of Nick Skelton

built with web standards and a baseline.