0

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?

2
  • why can't you use onload hook? Commented 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 :) Commented Oct 21, 2011 at 20:19

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You could probably just use the following:

if(window.location.href == 'http://www.mysite.com/thispage')
{
    //javascript for 'thispage'
}

Comments

0

How about putting the code in a script tag at the bottom of your pages and have some if checks on the location.href, like:

if(location.href == "/thisPage"){
   some code

 }

 if(location.href == "/thatPage"){
   some other code

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.