Where should JS scripts go in an HTML file?

后端 未结 6 1598
遇见更好的自我
遇见更好的自我 2020-12-14 01:48

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a

or add
6条回答
  •  别那么骄傲
    2020-12-14 02:31

    The whole HTML file is executed in the order it is written, that means

    
      

    changes the contents of the div, wherease

    
      
      

    does not, because the JS code is executed before the div has loaded.

    EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or

    
    

    Alternatively if you're using a JS library such as jQuery, you can use

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

提交回复
热议问题