简体   繁体   中英

HTML 5 defer attribute

I'm trying to understand async & defer HTML 5 attributes. Here is my testing code:

<body>
    <script type="text/javascript" src="script.js" **defer**></script>
    <div id="div1">
        Abc
    </div>  
</body>

script.js:

document.write("Hello World!")

As I understand, and according to the definition, "defer ... specifies that the script is executed when the page has finished parsing" shouldn't the output be:

Abc
Hello World! 

instead of

Abc 

which is the case?

Why does the document.write() not work with defer?

The answer "document.write clears page" doesn't take into account defer attribute. The resulting final answer is similar but my question was asked from another perspective.

If you open the JavaScript console on Chrome you will see the following message:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Not executing the document.write from deferred (asynchronous) script makes sense. Take into account this:

  • defer indicates the browser to wait and execute the code when the document has been loaded and parsed.
  • document.write writes to the document stream.
  • If document.write is called when the document is closed (loaded), then document.open is automatically called, the document is cleared and replaced with the content of document.write .

Preventing the execution of document.write within a deferred script will prevent the page/document from being cleared and only showing the content of the document.write .


Also there would be the question of "where should the content be written?" In your question you expect a result of Abc Hello World , but I would expect Hello World Abc as I would still expect the content to be written right after the script tag instead of at the end of the document.

It would be better to use a different method that will be supported in asynchronous cases and that will give you control over where the content will be placed, like for example appendChild or insertBefore .

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