Generating a Javascript Loader with Grunt

If you’re building a web application you’re going to end up with a sizable body of Javascript code, which you’ll usually want to keep separate until deployment. The best way to do this, that won’t require you to change the HTML on deployment, is to use a generated loader file that will load the full body of javascript code.

Recently I’ve made a Grunt Specific task for automating this based on ways I’ve done it in the past. It parses using Coffeescript but it’d be really trivial to change for your purposes. The script also assumes the presence of head.js You can find the Gist of it here: https://gist.github.com/MalucoMarinero/5473658

You can then configure it using options like the ones below.


  grunt.initConfig {
    loader:
      desktopClient:
        # The directory to look for javascript files.
        srcDir: 'www/clients/desktop/js'

        # The loader file to generate
        dest: 'www/clients/desktop/js/loader.js' 
        
        # Javascript files that must be loaded first due to dependency, when they
        # match they'll get pushed to the top of the head.js caal.
        priorityMatches: ['**/app.js', '**/module.js']

        # Patterns which will not get included in the loader. If the loader ends up in the source
        # you'll want to make sure the loader filename is in there.
        ignorePattern: 'loader.js'

        # A URL Prefix to make sure the filenames work in the browser. Without it all file paths
        # will be relative to the srcDir.
        prefix: 'js/'

        # What global variable the loader call will be attached to. This makes the loader a function
        # that can perform callback actions once the load is complete.
        varName: 'desktopLoader'
  } 

Once the loader is generated, on your HTML page all you need is to load that single loader.js file, and then run the function, at which point your application will come into being. Any initialisation that needs to be done after loading can be done by running the function with a callback.

When it comes time for deployment, the same HTML will be all you need, the loader will just point to a concatenated and minified file instead and everything will work as before. Hope you find it useful.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s