Why $ (document) is needed. Still needed after the <script> tag

Why is it $(document).readyreally needed after the tag <script>when using javascript.

What else if we do not use $(document).ready

+4
source share
3 answers

$(document).readyis javascript code, so it must be written in the element <script>even after jQuery is loaded.

If you are not writing $(document).ready, your code will not wait for the DOM to fully load and the javascript code to execute immediately.

script <head>, / DOM, ready, null/undefined. script <body>, , .

jQuery Docs

JavaScript , , , , . script , DOM . , .ready(), , DOM , jQuery. , CSS, .

, (, ), .

? !

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    alert($('#myname').val());
  </script>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />
</body>

</html>
Hide result

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    alert($('#myname').val());
  </script>
</body>

</html>
Hide result

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      alert($('#myname').val());
    });
  </script>
</head>

<body>
  <input type="text" value="Tushar" id="myname" />

</body>

</html>
Hide result

<script> <body> ready.

+15

$(document).ready <script> javascript.

.

, $(document).ready

-, , ready: , , , jQuery , jQuery, , .

JavaScript- script . script , , , script:

<script>
$("#foo").show();
</script>
<div id="foo" style="display: none">...</div>

, div , . ready .

, script: script </body>:

<div id="foo" style="display: none">...</div>
<!-- ... -->
<script>
$("#foo").show();
</script>
</body>

, script, . ready.

+10

, DOM ( ).

, , jQuery.

//Use ready() to make a function available after the document is loaded:
$(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle();
    });
});

. ready() , , .

jQuery

, . jQuery . $(document).ready() Document Object (DOM) JavaScript. $(window).load(function() {...}) ( ), DOM.

+1

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


All Articles