Inaimathi
Inaimathi

Reputation: 14065

Sometimes loading JavaScript

I'd like to conditionally load a set of javascript functions (which involve jQuery) on a given page.

The situation is that our site has a bunch of stuff that happens on $(document).ready (mostly fancy menu setup and a couple of CSS class manipulations), but one or two pages need more setup. It's enough code (and specific enough) that I don't want to just toss it into the main file, but rather just load it on those specific pages.

It seems that I can't do this by just loading a new file specific.js into those pages that contains

(function () {
   $(something).click(function () { Stuff(happens); });
   something(Else);
   ...
 } ());

In the above example, something(Else); works fine, but .click and .bind don't seem to do anything. What I ended up doing is

function specificStuff () {
   $(something).click(function () { Stuff(happens); });
   something(Else);
   ...
};

and adding if(specificStuff) specificStuff(); to the main js file. It works, but it seems like there should be a better way of accomplishing this (ideally one that would keep all the changes in specific.js and not touch the general settings).

Is there a canonical way of conditionally loading js code to run in document.ready?

Upvotes: 1

Views: 148

Answers (4)

You can call the jquery document ready function as many times as you need. I think your issue is with how you've set up your function. If you're trying to call the ready function, it should be like this:

$(function () {
   $(something).click(function () { Stuff(happens); });
   something(Else);
   ...
});

Also, if the something elements are created by your main.js file, you should include it before your specific.js file.

Upvotes: 0

The Scrum Meister
The Scrum Meister

Reputation: 30121

try removing the () when passing a function to document.ready:

(function () {
   $(something).click(function () { Stuff(happens); });
   something(Else);
   ...
 } **()**);

with the (), it will execute right away and not wait for the document to be ready.

Upvotes: 0

Achilles
Achilles

Reputation: 11309

You can call $(document).ready(); multiple times in a web page/script file. Just wrap your jquery bindings as such in your specific.js file:

$(document).ready(function(){ $(something).click(function () { Stuff(happens); }); something(Else);});

Upvotes: 2

Shane Daniel
Shane Daniel

Reputation: 959

You can load the page specific Javascript in the html of those pages, each script with its own document.ready function.

Upvotes: 0

Related Questions