开发者

Can you define jquery's $(function(){...}) twice on a page?

I am working on a web page that pulls an external javascript file that has all of my functions i开发者_JS百科n it. I'll call that file "functions.js".

functions.js has a jQuery has a $(function(){...}); to do my operations when the page is ready. My question is, is it possible to also write another $(function(){...} on the body of the same page that calls functions.js, so that whatever I do in both of the domReady functions happens on the page? For example, if functions.js is:

$(function(){
$('div').css('color','green');
}

and I put this code in tags on the page which calls functions.js:

$(function(){
$('div').css('background-color','red');
}

will the page end up making my divs have both green text AND red backgrounds, or will one override the other, or will neither work?

I hope this makes sense!


Yes, you can add as many $(document).ready() calls as you want: http://docs.jquery.com/Tutorials:Multiple_$(document).ready()


You could just try it you know (it would have taken less time than it did for you to type all of that out) :)

Yes, both will run and work.


Yes you can write as many ready functions as you like. You Do do not really need ready functions if you place your code before closing </body> tag and before jquery.js script.

Here's a well written blog on how document functions can slow you down and why they shouldn't be used. http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/


You can place as many as you like.

You can even place multiple $(window).load(function() { ... }) in jQuery (thanks cwolves).

In JavaScript (without jQuery), a workaround must be used...

(function() {
   var events = [];

   var registerWindowLoadEvent = function(callback) {
       events.push(callback);
   };

   window.onload = function() {
       for (var i = 0, eventsLength = events.length; i < eventsLength; i++) {
          events[i].call();
       };
    };
})();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜