javascript - When is a DOM element "ready"? -


this might sound silly question, , tend use:

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

but basic question.

let's have list of elements this:

<body>   <p>paragraph</p>   <div>div</div>   <div id="helloworld">hello, world</div>   <script>     var hw = $('#helloworld');     $(document).ready(function() {       // hw available me here     });   </script>   <p>another paragraph</p> </body> 

it seems div available, , don't run errors, there technically wrong this? not talking organized code, curious technical question @ hand.

so suppose question is:

is dom element considered complete , available browser reads it, regardless if rest of elements have loaded yet?

it seems div available, , don't run errors, there technically wrong this?

no. long script isn't run until after element exists, can access it. script in script tag that's after markup element refers consistently, cross-browser, able access element.

always works:

<div id="foo">...</div> <script>     $("#foo")... </script> 

never works:

<script>     $("#foo")... </script> <div id="foo">...</div> 

works only because jquery delays executing ready callback:

<script>     $(document).ready(function() {         $("#foo")...     }); </script> <div id="foo">...</div> 

this 1 of reasons the common recommendation put script tags @ end of document, before closing </body> tag. way, have access of elements defined above them. (and don't delay initial presentation of page, usually, though not always, want...)


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -