Using jquery what is the best way to load a snippet of code for a specific page without using an onload or on page load event? I have a js file that is included in differnet pages and this js file has custom jquery code in it, so some code is for one page and other code are for other pages. Instead of breaking them out into their own js code is there a way to have code run when a certain page is loaded?
-
why can't you use onload hook?Marek Sebera– Marek Sebera2011-10-21 20:17:06 +00:00Commented Oct 21, 2011 at 20:17
-
You could define a pageid on body/div container and just do a if($("#pageid").length) .. thats what i normally do :)Marco Johannesen– Marco Johannesen2011-10-21 20:19:05 +00:00Commented Oct 21, 2011 at 20:19
Add a comment
|
3 Answers
I'd suggest taking a look at Require.js as a form of dependency management. You'll have to break up your scripts into smaller chunks, but the require.js optimizing utility will bundle all those up into one request (so you don't have to worry about the overhead of multiple HTTP requests).
Yes, there's a small learning curve to using this library and it's a different architecture than what you seem to be currently doing, but you'll save yourself a ton in the long run..
- You will no longer be loading script that doesn't belong in that page
- Your scripts can be much more modular and use case specific
- You can bundle all single page dependencies into a single request (including the jquery lib)