Can you define jquery $ (function () {...}) twice on the page?

I am working on a webpage that retrieves an external javascript file that has all my functions in it. I will name this file "functions.js".

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

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

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

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

Will the page end with my divs having both green text and red backgrounds, or will one override the other or not work?

Hope this makes sense!

+4
source share
4 answers

Yes, you can add as many calls to $ (document) .ready () as you like: http://docs.jquery.com/Tutorials: Multiple _ $ (document) .ready ()

+5
source

You could just try what you know (it would take less time than you would to type all this) :)

Yes, both will work and work.

+3
source

Yes, you can write as many ready-made functions as you want. You really don't need ready-made functions if you put your code before closing the </body> and before the jquery.js script.

Here's a well-written blog about how document features can slow you down and why you shouldn't use them. http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/

+3
source

You can place as many as you want.

You can put some $(window).load(function() { ... }) in jQuery (thanks cwolves ).

In JavaScript (without jQuery) you need to use a workaround ...

 (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(); }; }; })(); 
+2
source

Source: https://habr.com/ru/post/1347654/


All Articles