开发者

Sometimes loading JavaScript

开发者 https://www.devze.com 2023-01-30 14:14 出处:网络
I\'d like to conditionally load a set of javascript functions (which involve jQuery) on a given page.

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 pag开发者_JAVA技巧es 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?


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);});


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消