简体   繁体   中英

Html & defer attribute

Having the code below:

<html>
    <head>  

        <script>            
            function elem_onload() {
                console.log("elem_onload");
            };      
        </script>

    </head>

    <body onload="elem_onload()">       
        <script type="text/javascript" src="script.js" defer></script>      
    </body>
</html>

script.js:

console.log("external script");

the defer attribute doesn't seems to work. The output is:

external script
elem_onload

whether with or without defer attribute. Shoudn't it be

elem_onload
external script 

with defer defined?

Duplicated answer!?

I'd like to state that my answer isn't duplicate of

How exactly does <script defer=“defer”> work?

The referenced recommended answer is about inline script where the browser behavior is clear for me - it simply ignores defer . My question is about external script in which case the browser should execute the external deferred script

after the document has been parsed

as documentation states hence after onload event.

So I'm waiting for an appropriate answer...

It is about the onload . Here's a definition of onload attribute, taken from this page .

The onload attribute fires when an object has been loaded.

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).

Hence, the onload function will execute after the content inside the body had been loaded, that is - after the inner script had executed.

I'm afraid that remdevtec answer isn't correct as he seemed to forget that I used defer attribute in the script tag while the definition says:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed

So in such a case (at least in my opinion) external script should be executed after onload , but it is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM