Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  68] [ 2]  / answers: 1 / hits: 68848  / 13 Years ago, wed, december 7, 2011, 12:00:00

I typically put all the JavaScript scripts into one file e.g. scripts.js (the less HTTP request, the better). So, as expected, some scripts are needed for some pages, some aren't.



To target a specific page, I use something like:



if ($(body#share).length > 0) {
// Place the logic pertaining to the page with ID 'share' here...
}

// The file / script continues...


Other or better suggestions? Thanks!



Clarification: I was not looking for the pros / cons between consolidating multiple JS files into one big file and keeping multiple separate JS files. The answer for this is surely 'depends on the situation' (we know that). My question is, assuming all my JS logic is placed into one big file, how do I make a particular (chunk of) script runs only when the corresponding page is loaded? One way I used to do is using if ($('#id-of-target-element')) { /* run the script */}; is there a better way?


More From » filesystems

 Answers
45

I like Paul Irish's approach... you don't have to follow it exactly, but the general idea is a very solid one.



It might look something like this for your example



Html



<body id=share>


Your page specific javascript



YourNamespace = {
share : {
init : function(){
// Place the logic pertaining to the page with ID 'share' here...
}
}
}


Paul Irish's Javascript that makes the magic happen



UTIL = { 
fire : function(func,funcname, args){
var namespace = YourNamespace; // indicate your obj literal namespace here

funcname = (funcname === undefined) ? 'init' : funcname;
if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
namespace[func][funcname](args);
}
},

loadEvents : function(){
var bodyId = document.body.id;

// hit up common first.
UTIL.fire('common');

// do all the classes too.
$.each(document.body.className.split(/s+/),function(i,classnm){
UTIL.fire(classnm);
UTIL.fire(classnm,bodyId);
});

UTIL.fire('common','finalize');
}
};

// kick it all off here
$(document).ready(UTIL.loadEvents);


So the line you see directly above will kick off the following



YourNamespace.common.init()
YourNamespace.share.init()
YourNamespace.common.finalize()


Have a read of his blog post and a few of the variations linked from it.


[#88707] Tuesday, December 6, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;