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?
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 :-)
Only load JS when it's needed. Within each JavaScript file, make sure that only code that gets used is included. Additionally, you may not need to load every JavaScript file on every page of your site.
A . js file is an ordinary text file that stores your JavaScript scripts. You can store one or more of your JavaScript scripts in a single . js file and access them from multiple HTML pages.
There are two ways to include jQuery in a project, which is to download a local copy or link to a file via Content Delivery Network (CDN).
Projects In JavaScript & JQueryYes, you can use multiple versions of jQuery on the same page.
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).
I've recently grappled with this problem when re-starting development of a very involved web app. I decided on several patterns:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With