Is there a better way to organize javascript in a single file with specific code for multiple pages?

I have several websites where I use a relatively small amount of jQuery to do different things on the pages. Usually we talk about a few dozen lines of code on a page.

I save all my JS in one file until it is huge and clearly defined enough. However, what I aspired to organizes it like this:

$(document).ready(function(){ var onPage1 = $("#id_thing_on_1").length === 1; if( onPage1 ){ var usefulPage1Function = function(){}; //blah $("a").click(function(){}); //etc } }); $(document).ready(function(){ var onPage2 = $("#id_of_page_2").length === 1; if( onPage2 ){ $(".someClass").fadeIn().click(function(){}); //etc } }); 

Everything that is used on several pages is taken out to the library, but for specific pages, this is the template that I followed. Is there a better approach or is it good practice to store JS in a single file and load it on multiple pages?

+3
javascript jquery
Dec 07
source share
4 answers

I would be interested to know a different opinion on this issue, but what I did to organize and execute the correct set of JS code for each page is to have some kind of routing mechanism as the basis of my js application, where I add the list " controller ", which each section adds to it, and the routing mechanism calls the controller.init () method, based on the URL.

 myApp = {}; (function(app, $) { var defaultController = "Default"; var routes = []; routes["Default"] = defaultController; var currentControllerFromUrl = function() { // match urls in the form ../mvc/controllerName.mvc/... var re = new RegExp(/\/(\w*)/i); var m = re.exec(document.location); if (m == null) { return null; } else { return m[1]; } }; var currentActionFromUrl = function() { // match urls in the form ../mvc/controllerName.mvc/action/ var re = new RegExp(/\/mvc\/\w*.mvc\/(\w*)(\/|\b)/i); var m = re.exec(document.location); if (m == null) { return null; } else { return m[1].toLowerCase(); } }; var currentWebPageFromUrl = function() { var re = new RegExp(/\/(\w*).html/i); var m = re.exec(document.location); if (m == null) { return null; } else { return m[1]; } }; var populateControllerRoutes = function(app) { for (var ctl in app.controllers) { routes[ctl] = ctl; } }; var theApp = { controllers: {}, run: function() { this.initController(); }, initController: function() { var urlController = currentWebPageFromUrl(); // populate routes populateControllerRoutes(this); if (urlController && routes[urlController]) { // load the correct controller into the activeController this.controller = new this.controllers[routes[urlController]](); this.controller.init(); var action = currentActionFromUrl() || "index"; if (action && this.controller[action + "Action"] !== undefined) this.controller[action + "Action"](); } } }; window.myApp = $.extend(app, theApp); })(myApp || {}, jQuery); // and somewhere else (function($) { myApp.controllers.default = function() { this.init = function() { }; this.indexAction = function() { // index action init $("#res").text("hi there!"); } } })(jQuery); $(function() { myApp.run(); }); 

With this approach, the controller functions do not have to be in the same file, so during development you can conveniently store your controller functions in separate files and as part of the assembly / deployment, combine them and minimize their single JS file.

+3
Dec 07 '10 at 1:12
source share

Here is one way to reduce redundancy in your code:

 $(document).ready(function(){ function page1() { var usefulPage1Function = function(){}; //blah $("a").click(function(){}); //etc } function page2() { $(".someClass").fadeIn().click(function(){}); //etc } var pages = [ [ '#id_thing_on_1', page1 ], [ '#id_of_page_2', page2 ] ]; for (var i = 0; i < pages.length; i++) if ($(pages[i][0]).length === 1) pages[i][1](); }); 
+1
Dec 07 '10 at 1:14
source share

You do not need js download cost. But actually it depends on the usage pattern of your site. If most page downloads occur, for example, on the home page, then merging and mining all your js into one file for this page may make sense. If the unique code remains small, then your approach sounds. This illustrates the natural tendency of the code to weaken the structure during its optimization.

0
Dec 07 '10 at 1:16
source share

Can you tell us why you want to put different page codes in one file, given the fact that you are 100% sure that these codes will not be executed, in fact you spend time creating code / controller to avoid execution this unrelated code.

Also, how many pages you say, if it's only 2 pages, then you should be fine. But what if 50 pages? What if 20 pages use the same code that your controller will look like? Or are you going to copy the same code 20 times?

HOWEVER, having all the codes in a minified single file seems to load faster than the browser initiating multiple downloads. You must have a balance between VS VS coding practice.

I tend to have different js files with special code for different pages, so unrelated codes do not load.

Any common code, I put it in specific js lib files, so most of the unrelated lib code doesn't load.

Eg.

 Search page will have: search_page.js util.js form_validation.js Result page will have result_page.js util.js lib_map.js 

Just my $ 0.02

0
Dec 07 '10 at 1:24
source share



All Articles