Defer attribute and onload event

后端 未结 2 861
清酒与你
清酒与你 2021-01-03 09:19

Having the code below:


      

        

        
相关标签:
2条回答
  • 2021-01-03 09:39

    The external script deferred by the defer attribute is executed before the (DOMContentLoaded) is fired, i.e. when the initial HTML document has been completely loaded and parsed. The onLoad attribute on a <body> tag, on the other hand, fires only when a web page is fully loaded.

    Therefore, the defer attribute is indeed working. You may test it by trying the two cases below. In both cases the content of script.js file should be this:

    console.log(document.getElementById('sample').innerHTML);
    

    CASE 1 HTML - with defer --> logs "Sample text"

    <body onLoad="elem_onload()">       
    <script type="text/javascript" src="script.js" defer></script>    
    <div id="sample">Sample text</div>
    </body>
    

    CASE 2 HTML - without defer --> logs an error

    <body onLoad="elem_onload()">       
    <script type="text/javascript" src="script.js"></script>    
    <div id="sample">Sample text</div>
    </body>
    
    0 讨论(0)
  • 2021-01-03 09:44

    Thx. all for help.

    So the statement "...after the document has been parsed" from original doc. (MDN <script> tag) refers say step #0 from 12.2.6 The end

    when document is completely parsed and now there are several tasks to be done on that occasion. Those tasks includes running external deferred scripts which is prior (#3) to onload event.

    Am I right?

    0 讨论(0)
提交回复
热议问题