JavaScript dynamic library loader

There are coutless examples of dynamically loading libraries, but almost all of them follow a very rigid pattern. It’s very difficult or awkard to specify where you want the files loaded.

E.G. Maybe you need the library loaded into the <body> insted of the <head>.

I needed something really simple where I could specify where all the libraries are stored and then tell the loader where they must go via querystring (actually just the “?” part). In principle, this follows the same ideas I put together last year on building dashboards.

WARNING: The WordPress source code formatter really screws up things here and there (adding extra spaces, removing quotes, changing > to &gt; etc…) Check for errors before using this code.

For this example, here is the convention (this all goes in the <head> tag) :
First the location of all the script libraries

<script type="text/javascript">
	var scriptDir = "../lib/shared/js/";

Then call the loader with all the libraries…

<script type=”text/javascript” src=”setup.js?head[lib1,lib2,lib3]body[lib4,lib5]“></script>

What does this do? Basically lib1.js, lib2.js and lib3.js are called into the head (note the “.js” extension and folder location is absent).

This is the same as calling …

<script type=”text/javascript” src=”../lib/shared/js/lib1.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib2.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib3.js”></script>

… in the <head> tag and …

<script type=”text/javascript” src=”../lib/shared/js/lib4.js”></script>
<script type=”text/javascript” src=”../lib/shared/js/lib5.js”></script>

… in the <body> tag.

And here’s the script for “setup.js” :

// Get the head and body tags

// Find the first instance (index = 0) of the head tag
var he = document.getElementsByTagName(“head”)[0];

// Find the first instance of the body tag
var bo = document.getElementsByTagName(“body”)[0];

// Find all script tags
var j = document.getElementsByTagName(“script”);

// Find this file “setup.js”
for (var i=0;i -1)
// Get everything inside the “head[…]”
// portion separated by comma and put into an array.
var fh = f.match(/head\[(.*?)\]/)[1].split(‘,’);

// For each instance of a library, call the loader
for(var i=0; i < fh.length; i++) loadJS(l + fh[i] + ".js", true); } // If there are scripts going in the body tag... if(f.indexOf("body[") > -1)

// Get everything inside the “body[…]” portion
// functionality is the same as above
var fb = f.match(/body\[(.*?)\]/)[1].split(‘,’);

// For each instance of a library, call the loader
for(var i=0; i < fb.length; i++) loadJS(l + fb[i] + ".js", false); } } catch(err) { // Do nothing } } // Script loader function loadJS(p, h) { // Create a tag var s = document.createElement('script'); s.type = 'text/javascript'; s.src = p; // If "true" I.E. it goes in the ... if(h) he.appendChild(s); else bo.appendChild(s); }[/sourcecode]


6 thoughts on “JavaScript dynamic library loader

    • Hehehe!

      BTW… (Not rushing you or anything) would you happen to have an ETA on that?

      Also, have you settled on a design pattern for the code yet?

      • I don’t have a hard ETA quite yet…I just got back to Atlanta last night (WOO!), but am technically working on finishing up a project that I’ll be presenting over Skype on Tuesday. :P

        After that, then yeah, I plan on diving into CMS development.

        The more I’ve thought about it, the more I like Drupal’s approach – every single bit of functionality is an independent node, sort of like your suggestions a few months ago to represent the backend as a neural net. Thus far I’ve envisioned an interconnected set of nodes that is in contact with all the other nodes it needs in order to perform its functions.

        So, as for a design pattern…something along the lines of a Singleton creation pattern with a decentralized chain of responsibility on the structural end.

        Obviously this is still very much in the planning phase – what are your thoughts?

      • My grasp of PHP is obviously no match to yours, but I would keep the Singleton patterns to Database and User classes.

        You’re still going to be the same user irrespective of where you visit on the site. And you only need one instance of a database as well.

        Maybe user classes for CurrentUser and User where the first is a Singleton that inherits from the second? The User class could be a generic Prototype. I came across something similar by Dave Tufts.

        I did play around with that idea of “everything is a node” before and even built a database layout to match. I just never got a chance to develop it, but maybe you can take something from it.

        In my project, everything was a type of node :
        A Section
        A Page
        A Pagelet

        Sections and Pages could be nested via parent_id.

        How the content is created, grouped and formatted depends on which module was used to edit the content (template_variant field would come into effect to make this possible as well).

        E.G. :
        When using a “Forum module”…
        In a discussion board, each “Category” would be a Section.
        Each “Forum” a sub Section
        A “Topic” is a page and each “Reply” a Pagelet.

        When using a “Blog module”…
        The “Blog” would be a Section.
        A “Blog post” is a page (with multiple pages possible via parent_id).
        And each “Comment” is a Pagelet.
        (With the added benefit of being able to create sub Blogs)

        When using a “Shop module”…
        Each “Department” is a Section or sub Section
        A “Product” is a Page with variations as sub Pages.
        And a buyer comment is a “Pagelet” maybe?

        Well, you get the idea..

        And, of course, each module would make good use of the “Param” field and custom fields for required content.

        Maybe in the future, someone could create a “Document manager” (which is why I included the “file” field on the Pages. The point is to make it possible so the module can be dropped in and be used right away without fiddling around.

        The idea was to be content agnostic as much as possible on the database end while allowing an unlimited hierarchy of content and content types.

        Hope that makes sense…

        I also played around with workflows (something borrowed from Joomla! :P), but I wanted to create custom status types.

        A “Contributor” would create an article as a “Draft”.
        An “Editor” would approve and publish as “Published” or “Pending”.
        Or a dedicated “Publisher” would do the publishing.

        I thought it best not to restrict user groups on how someone would use the software. A custom workflow like the above with different status types would let them mould it to their particular internal organizational structure.

        I don’t know if this is the most efficient DB design, but at the time, it seemed to make sense ;)

  1. Pingback: It’s design time « Theatre of Consciousness

  2. Pingback: It’s design time »

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s