I am just starting to learn JS. So, correct if I misunderstand something. There is such jquery code:

$(document).ready(function () {...}); .

I understand this event, which starts after downloading the html code. I need to write the code in the event before loading html and all the rest. I understand that the easiest way is to heraknut somewhere in the middle of html - <script>...</script> , but this doesn’t look aesthetically pleasing =) I used the following code:

 $(window).on('load', function () {...}); 

Am I correct? If not, then how?

  • What exactly are you trying to do? - Pleshevskiy
  • @Pleshevskiy, Preloader. As soon as the content is uploaded it should disappear - Alyoshka Lavrushka
  • So what does $(document).ready not like? - Pleshevskiy
  • @Pleshevskiy, but the code will then be executed as soon as the content is loaded. There are just a couple of things in the code that must be performed before downloading the content - Alyoshka Lavrushka
  • I do not understand what I mean. The preloader is usually done on pure css. If you have a js, then at the very end of the body tag we put the script and you can call without $(document).ready - Pleshevskiy

1 answer 1

I need to write the code in the event before loading html and all the rest.

Register in the head

  <script src="/path/to/file.js"></script> 

In the file file.js without DOM ready wrappers write.

 $(window).on('click', '.element', function() { // some code }); 

This event will always trigger on elements with the .element class, even if the element is dynamically added.

As this approach progressed in different versions of jQuery :

 $( selector ).live( events, data, handler ); // jQuery 1.3+, deprecated: 1.7, removed: 1.9 $( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+ $( document ).on( events, selector, data, handler ); // jQuery 1.7+ 

PS Replace the click event with what you need, you can use spaces.