Modularizing jQuery’s $(document).ready()
While domready-type events are a welcome addition to modern JS programming, many people abuse them by dumping all of their code in there. This keeps the script overhead of your pages high when often pages only need certain functionality. There are plenty of approaches to modularizing you initialization code, but a simple approach built off of <body> ids is my go-to method.
The first step to this approach is setting up page-specific Javascript as an object literal:
- var init = {
- common: function() {
- // insert common js here
- },
- home: function() {
- // insert js for <body id=”home”> here
- },
- // etc
- }
Then inside of your $(document).ready() function call your common js code and let the current body tag id dictate what code is loaded:
- $(document).ready(function() {
- // execute code common to every page
- init.common();
- // use the body’s ID to call page-specific js if it exists
- $.isFunction(init[document.body.id]) && init[document.body.id]();
- });
You’ll notice line #5 checks if the initialization function exists before calling it. This keeps you from having to make empty placeholders in your object literal for pages that don’t need anything. You could also get a lot more sophisticated by splitting each page’s JS into init, core, and teardown code or making them fire via custom events, but you get the point.