Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html & defer attribute

Tags:

javascript

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...

like image 665
Mulligan81 Avatar asked Nov 20 '22 18:11

Mulligan81


1 Answers

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.

like image 137
guysigner Avatar answered Nov 23 '22 08:11

guysigner