Defer attribute and onload event

后端 未结 2 946
清酒与你
清酒与你 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 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"

           
        
    
    Sample text

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

           
        
    
    Sample text

提交回复
热议问题