我有一个片段,放置在任何网站内,在文档中间,就像在文章中间,而不是在 <head>
内。 。此脚本通过附加 <script>
在我的域上加载外部脚本。标签(与谷歌分析片段非常相似)。
我的问题是,如果该脚本放置在正文中,DOM 是否尚未被解析,因此我可以安全地假设在评估脚本时我可以操作 DOM,而无需等待 DOMReady 事件?
我这么问是因为当我的脚本开始执行和 DOMReady 事件触发时会有很大的延迟(请参见棕色条)。我正在使用这个DOMReady implementation
托管网站
<html>
<head>
...
</head>
<body>
Website content
...
<div>
<!-- Snippet -->
<div id="myContainer"></div> <!------(I should be able to query this div) -->
<script type="text/javascript">
function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'http://example.com/script.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- Snippet End -->
<div>
More content
...
</body>
</html>
example.com/ script.js
(function(){
//by this time div#myContainer should exist, right?
var div = document.getElementById('myContainer');
div.innerHTML = "Hello World!";
})();
一些注意事项:
- 我无法控制主机页面,它可以包含任何内容。
- 对旧版浏览器的支持是一个问题。
- 我应该能够尽快附加内容,我迫不及待地等待其他库和图像等内容完成加载。
- 它应该每次都能可靠工作。
最佳答案
是的,没错。如果正文底部有一个脚本标记,那么当脚本运行时,所有内容都会在此之前呈现。
W3Schools 有一篇关于这个主题的好文章。
<head>
中的脚本
block 引用>Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.
<body>
中的脚本block 引用>If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.
关于javascript - 当脚本在主体树中执行时,DOM 准备好了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40876535/