Monday, January 8, 2007

Simple JavaScript bootstrap solution

As WebSiteOptimization suggests external JavaScript files should be included "one time for all".
There are a lot of procedures to do that, using a server-side script to include and compress required files.
This simple anonymous function should do something like dynamic JavaScript inclusion, based on unobrtusive cross-browser function and really simple to use.

The concept is this one:
when You add a script on Your page this will be exactly the last script present on document so You could do some operation using its source.

bootstrap.js does it, and works as "includer" from first file name to last.


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

In this example bootstrap will include jsfile.js that's inside jsfolder so You just need to include bootstrap.js file inside your dedicated JavaScript files folder.

You could load multiple JS too, using char "|" as separator

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init"></script>

In this case bootstrap will load jsfile.js, then otherfile.js and finally init.js, everyone automatically from folder jsfolder.

// bootstrap resulting string for inclusion
jsfolder/jsfile.js
jsfolder/otherfile.js
jsfolder/init.js


If You need to include files with a different extension, You could simply add a suffix after last file name.

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init#php"></script>

// bootstrap resulting string for inclusion
jsfolder/jsfile.php
jsfolder/otherfile.php
jsfolder/init.php


Then, for example, You could pack your js code using my overbyte Editor and call saved php files quickly.

You can use any kind of extension, then PHP is not required.

You can use more than one bootstrap too, copying bootstrap.js file inside every dedicated javascript folders.

Could be this an unobtrusive and alternative way to include dynamically your libraries and functions ? ... and it's less than 500 bytes :-)

Update
Now GzOutput php class supports something like bootstrap for JS, CSS and other kind of files.

You can test PHP 4 version or PHP 5, successful tested on E_ALL | E_STRICT error_reporting enviroment.

No comments:

Post a Comment