My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Tuesday, April 03, 2007

Semantic Import

With MetaDOM style I wrote a little function to add runtime external scripts, this time compatible with all modern browser ;)

This function is similar with Python import syntax, using From to specify a folder, or why not an uri, Import to add one or more script and finally an optional And method to call a callback on scripts loaded.

Here You can view an example
From("jsFolder") . Import("MyScript", "MyOhterScript")


Seems cool?
The first goal is to add dynamically one or more script in a simple and fast way.
These script will be available on onload event if they're imported before this event.
These scripts should be available on DOMContentLoaded too, but to be sure these script will be available You could add a callback using last method.

From("jsFolder") . Import("MyScript", "MyOhterScript") . And(DoStuff)


DoStuff is a function that do something with loaded scripts.

What else You should do?

You could load different extension files using second From argument:
From("jsFolder", "php") . Import("MyScript", "MyOhterScript")


This code will load files jsFolder/MyScript.php and jsFolder/MyOtherScript.php so You could use this second argument to add variables (Remote Scripting using GET) or load scripts without cache problems.

From("jsFolder", "js".concat("?", Math.random() * 123456789)) . Import("MyScript")


Do You need an example page?
Here there's basic example using a callback while in this page there's an uncached dnamic script load.

I hope You'll like this "Python style" like JavaScript function and finally, You could even load external scripts using an uri instead of folder

From("http://example.com/js").Import("HisScript")



Update - 13/04/2007
I uploaded last revisited version in devpro.

This version fixes different external sources size problem and calls specified callback only when every external script is completely loaded and is available.

This last version send as callback arguments every script created to include each external source.

Please visit new demo page to view an example, where 2 external sources are loaded (forced without cache) and have different sizes :)

1 comment:

Unknown said...

This is pretty cool Andrea.