Boilerplate JavaScript Document

When creating a new javascript document, there are several principles you should keep in mind. I was disappointed to see there were no clear and obvious boilerplates for getting started on a new javascript document so I've put this one up for reference.

(function() {
    'use strict';
    // add your event handlers here
    document.addEventListener("DOMContentLoaded", function(event) { 
        //do work
    });
 
}());

If you need to pass an object to your closure, like jQuery for example, you can do like so. Notice we pass in the jQuery object and rename it as "$" inside the anonymous function.

(function($) {
    'use strict';
    // add your event handlers here
 
    $(document).ready(function() {
        // add your event listeners here
    });
 
}(jQuery));

If you are using jQuery mobile, you will probably need a pagechange listener as well

/*globals document, jQuery, console */
(function($) {
    'use strict';
 
    $(document).ready(function() {
        // this fires once after the DOM has loaded
    });
 
    $(document).on('pagechange', function() {
        // this fires once each time a jqm app goes through an internal page transition
 
    });
 
}(jQuery));

Even angular which is super conscious of scope and context will run just fine from within a closure.

/*globals angular */
(function() {
    'use strict';
 
    angular.module('someApp')
        .run(function($rootScope, userService) {
            var auth;
 
            $rootScope.$on('$routeChangeStart', function (event, next) {
                //this fires each time angular goes through an internal page transition
                auth = userService.isUserAuthenticated();
                console.log(event);
                console.log(next);
                console.log(auth);
            });
        });
}());

If you are wondering about the comment at the top, that's added for sublime-jslint so it doesn't give a warning about global variables you're working with, such as jQuery, console and document. If you write JavaScript for a living and don't use a linter, you got to get on that! It's great for keeping your javascript clean and concise and also has a run on save feature that's keeps your code clean as you go. To install this package, follow these steps

  • Make sure you have package control set up for your sublime installation - https://packagecontrol.io/installation
  • Restart sublime
  • Enter cmd+shift+p to open your package controller
  • Enter"pci" into the prompt and select "Package Control: Install Package"
  • Search for and install sublime-jslint
  • Once installed, go to Sublime Text 2>Preferences>Package Settings>JS Lint>Default Settings and update this line "run_on_save": true,

Now open any typical javascript file you have and hit cmd+s and you should get a prompt at the bottom of your sublime window telling you about any errors or warnings it found in your js document.