Bootstrapping JavaScript functions

Tags:

At the moment I am working on a small JavaScript project which does interact extensively with the DOM. One goal in this project is simple integration with the document it shall work on. The preferred way of injection will be to just include the script in the head of the document and then the script does its "magic". This requirement combined with extensively interaction with the DOM does provide some challenges. The main issue which needs to be challenged in such a combination is to be sure the DOM are ready before the script starts to interact with it. Another challenge in this project is that I cannot use any of the JavaScript frameworks around. I ended up writing a bootstrap script.

Accessing elements in DOM with JavaScript before the element is loaded is not possible and when writing a script interacting with the DOM there are several ways of handling this. Some good, and some bad, and when trying to meet the requirement of easy injection into a page I needed something which would make sure no functions fire before the DOM is available.

Using the script

The bootstrap script is pretty easy to use; create a new bootstrap object and attach the functions which are going to work on the DOM to the object and the bootstrap will fire the functions in attached order when the DOM is ready.


<script type="text/javascript" src="bootstrap.js"> </script>
<script type="text/javascript">

    // Function which need to access the DOM
    function doSomething(el){
        var e = document.getElementById(el);
    };

    // Init bootstrap
    var boot = new bootstrap();
    boot.attach('target',doSomething);

</script>

<div id="target">
    Do something on this element
</div>

Here is an example of the script in use.

A fully documented version can be found here and a compressed version can be found here (ca 0.7kb). Here is the js doc for the script.

What the script does

The script is pretty simple. First the script has an internal array which holds the attached functions. Then there is a load function which will run trough the array of attached functions and execute each function when the DOM is ready.

The "DOM readiness" is handled by the DOMContentLoaded event in Opera 9.x, FireFox 2.x and Safari 3.1.1x. For IE I use Diego Perini's trick to detect "DOM readiness". If none of those methods work it will fall back to using the onload event for trigging the load function which executes the attached functions.

Please feel free to grab, modify and use as you wish.

Comments:

Post a Comment:

HTML Syntax: NOT allowed