Skip to content

Instantly share code, notes, and snippets.

@timmywil
Created June 20, 2011 21:46
Show Gist options
  • Save timmywil/1036661 to your computer and use it in GitHub Desktop.
Save timmywil/1036661 to your computer and use it in GitHub Desktop.
On a medium-sized site, you may want your javascript all in the same file, but only process certain functions based on element presence.
/**
* Internal page management
* Add selector-dependent js to the array
* or call page to execute all js relevant to the current page
* @param {String} selector A jQuery selector
* @param {Function} fn A function to execute if sel is present on the page
*/
var pages = [];
var page = function( selector, fn ) {
var cur, $sel;
if ( selector ) {
pages.push({ selector: selector, fn: fn });
} else {
while ( cur = pages.shift() ) {
$sel = $(cur.selector);
if ( $sel.length ) {
cur.fn.call( $sel, $sel );
}
}
}
};
page("#foo", function() {
// This only runs on a page with the element #foo on it
});
page("#someTable td", function() {
// The context of this function is the jQuery selection
this.each(function() { });
});
page("#someForm", function( $form ) {
// Conditionally load scripts that pertain only to #someForm
// The selection is also passed as an argument( $form )
require([ 'jquery.validate' ], function() {
$form.validate();
});
});
$(document).ready(page);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment