jQuery/JS for different pages - best way of doing this?

javascript, jquery

Solution

Personnally I like to have one file with all the things needed in it. It's better because once loaded, the browser can cache it and you don't care anymore.

As for coding, I may write pieces of code in different files, which I build as a single file for production.

This way, all your code is accessible anytime.

Nevertheless, you may include tags in your views/templates, so that you can trigger certain functions only on particular views/pages.

For example :

myObject = { 
    myFunctionForArticles : function(){ $('.article').each(...); },
    myFunctionForCategories : function(){ ... }
};

And within the Article view :

<script type="text/javascript">
    myObject.myFunctionForArticles();
</script>

Make sure your included javascript keeps very thin and general though. More than one liners calling a general function can lead to trouble. In theory it is not something you might call a best-practise. Choose what you feel is the right balance between tidyness and easiness to maintain (if you have few views, maybe you can make, along with the one big file containing all the heavy stuff, some short and specific js files, which are called only by the right view to trigger the right functions at load time ; if you have a lot of views, maybe including one-liner inline js tags will save you the burden to maintain a lot of short files).

Problem

Apologies if this is a silly question, and I'm not even sure of the best way of wording it... At the moment I have a site with maybe 20+ different uses of jQuery, all varying from page to page. I'm just wondering what the best way is to store this code? - Everything in one big jquery.myfunctions.js file? And check if the element exists for each statement? - Embed script tags into each individual page? - Use PHP to deliver different content into script tags kinda like the above? - Separate .js files per page? ims I don't like the sound of this at all To be honest, I'm not even sure if jQuery does this for you, so it's okay to have multiple `$('#whatever').function()` loaded onto each page without any noticeable performance issues? Any advice on this would be fantastic, probably a silly question but I want to do things the 'proper' way you know? Thanks :-)

Original source