I’ve got a fairly large site, with a lot of jQuery code for lots of different pages. We’re talking about 1000 lines of fairly well optimized code (excluding plugins).
I know jQuery is fairly good at ignoring listeners for page elements that don’t exist, but it still has to test their existence when the page loads. I’m also creating a load of vars (including decent sized arrays and objects), but only a few of them are used on each page.
My Question is: What’s the best method of cutting down the amount of work each page has to do?
However, I do NOT want to split up the code into separate files. I want to keep all my code in 1 place and for the sake of efficiency I only want to call the server to download JS once (it’s only 30kb, smaller than most images).
I’ve thought of several ways so far:
- Put all my code chunks into named functions, and have each page call the functions it needs from inline <script> tags.
- Have each page output a variable as the pageID, and for each chunk of have an if statement:
if (pageID = 'about' || pageID = 'contact') {code...} - Give each page (maybe the body tag) a class or ID that can be used to identify the chunks that need executing:
if ($('.about').length || $('.contact').length) {code...} - Combine 1 and 2 (or 1 and 3), so that each page outputs a variable, and the
ifstatements are all together and call the functions:if (pageID = 'about') {function calls...}
Any other ideas? Or which is the best/most efficient of those?
Your first option will be fastest (by a minute margin).
You’ll need to remember to call the functions from the correct pages.
However, don’t bother.
Unless you’ve measured a performance impact in a profiler, there is no need to optimize this much.