Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Created September 8, 2013 18:17
Show Gist options
  • Save mojaray2k/6487133 to your computer and use it in GitHub Desktop.
Save mojaray2k/6487133 to your computer and use it in GitHub Desktop.
Here is one simple way to keep your code in check and avoid bugs: write a page routing function that executes only the JS that is needed for that particular page.
var route = {
_routes: {}, // The routes will be stored here
add: function(url, action) {
if( typeof url === 'string' ) { // if url isn't an array, convert it to an array
url = [url];
}
for (var i=0; i<url.length; i++) { // loop over the array elements
this._routes[url[i]] = action;
}
},
run: function() {
jQuery.each(this._routes, function(pattern) {
if (location.href.match(pattern)) {
// "this" points to the function to be executed
this();
}
});
}
}
// array as url parameter
route.add(['002.html','003.html'], function() {
alert('Hello there!');
});
// array as url parameter
route.add(['products.html','services.html'], function() {
alert("this will be executed :)");
});
// string as url parameter
route.add('singlepage.html', function() {
alert("this will be executed, too :)");
});
// log the generated variable route._routes
console.log(route._routes)
route.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment