HTML 5推迟属性 [英] HTML 5 defer attribute

查看:198
本文介绍了HTML 5推迟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 async & 推迟 HTML 5属性。这是我的测试代码:

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:

script.js:

document.write("Hello World!")

据我了解,并且根据定义,defer ...指定在页面完成解析时执行脚本不应该输出:

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! 

而不是

Abc 

是哪种情况?

为什么 document.write()无法使用延迟?

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

答案document.write清除页面没有考虑延迟属性。最终得到的答案是类似的,但我的问题是从另一个角度看问。

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.

推荐答案

如果您打开JavaScript控制台在Chrome,你会请参阅以下消息:

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 表示浏览器要等待并执行代码文档加载和解析后。

  • document.write 写入文档流。

  • 如果在关闭(加载)文档时调用 document.write ,则会自动 document.open 调用时,文档被清除并替换为 document.write 的内容。

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

在延迟脚本中阻止执行 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.

还有一个问题是内容应该写在哪里? 在您的问题中,您期望得到 Abc Hello World 的结果,但我希望 Hello World Abc ,因为我仍然期望要在脚本标记之后而不是在文档末尾写入的内容。

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.

这将是最好使用在异步情况下支持的不同方法,这将使您可以控制内容的放置位置,例如 appendChild insertBefore

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.

这篇关于HTML 5推迟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆