When should you use $ (document) .ready?

I noticed that there was $(document).ready(..)a noticeable delay in applying javascript effects. However, I also understand that simply having an effect in <script>may not always work, because the DOM may not be ready.

When do you always put your code in $(document).readyand when can it be displayed in a global tag <script>?

+3
source share
4 answers

There is no rule for when you should and should not use it. The answer is whether your code should cross parts of the DOM that will not exist when it is executed. If you need to find an element by ID, you can use it to allow the DOM to be created before your code is executed. If you do not care about the DOM, you do not need to use it.

Another approach is to move the script tags to the end of the body tag so that they run after the DOM loads. There is no main advantage / disadvantage for this in any case, but it makes it difficult to save your code, using $ (document) .ready () allows you to keep javascript at the head of your page, even if it needs to be done at the end.

+3
source

, $(document).ready(func) $(func), . , - .

... . ( , ) , .

, /, $(window).load(func) .

+2

DOM (.. ), , DOM . , , / , . $(document).ready() .

0

, $(document).ready(..) DOMContentLoaded Load:

http://api.jquery.com/ready/

, $(document).load(..) DOM, , , (, ).

$(document).load(..) <script> JS , ? script.

Have you tried putting the global tag <script>at the bottom of the page and running it in two different scripts - once using only the function $(document).load(..)in it and again with the contents of the load function in the script instead. Is there a significant difference in JS effects between the two cases?

0
source

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


All Articles