Another interesting structure for WordPress theme JS is to use DOM-based routing, where custom JS code can be placed in the common function (output everywhere), or output on particular pages based on body class. It’s important to note that in the example file, body classes containing a dash should be changed to use an underscore.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ======================================================================== | |
* DOM-based Routing | |
* Based on http://goo.gl/EUTi53 by Paul Irish | |
* ======================================================================== */ | |
(function ($) { | |
var Whitespace = { | |
common: { | |
init: function () { | |
// Run everywhere. | |
}, | |
finalize: function () { | |
// Run everywhere. Loaded last. | |
} | |
}, | |
home: { | |
init: function () { | |
// Run on page with body class `home`. | |
} | |
}, | |
code_snippets: { | |
init: function () { | |
// Run on page with body class `code-snippets` (change - to _) | |
} | |
} | |
}; | |
var util = { | |
fire: function (func, funcname, args) { | |
var namespace = Whitespace; | |
funcname = (funcname === undefined) ? 'init' : funcname; | |
if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') { | |
namespace[func][funcname](args); | |
} | |
}, | |
loadEvents: function () { | |
util.fire('common'); | |
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function (i, classnm) { | |
util.fire(classnm); | |
}); | |
util.fire('common', 'finalize'); | |
} | |
}; | |
$(document).ready(util.loadEvents); | |
})(jQuery); |
Leave a Reply