简体   繁体   English

当document.body存在时执行js

[英]Execute js when document.body exists

I have some script in document HEAD section like this. 我在文档HEAD部分中有这样的脚本。

<html>
<head>
    <title>Javascript Tests</title>    
    <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);
    </script>
</head>
<body>
</body>
</html> 

In this script i want to add element to body, but it fails with document.body is null exception. 在此脚本中,我想将元素添加到主体,但由于document.body为null异常而失败。 I understand that body doesn't exist at this time. 我知道该身体目前不存在。 But i still need do this operation, because a can't insert this script to body, it restricted by API, i haven't access to all site code. 但是我仍然需要执行此操作,因为无法将此脚本插入正文,受API限制,我无法访问所有站点代码。

And important one: i need do this before window will be loading (i mean window.load event). 重要的一点:在窗口加载之前,我需要执行此操作(我的意思是window.load事件)。

Can I do this? 我可以这样做吗?

If you don't want to use Jquery you can use DOMContentLoaded see reference here 如果您不想使用Jquery ,则可以使用DOMContentLoaded 请参见此处的参考。

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading 当文档完全加载并解析后,无需等待样式表,图像和子帧完成加载,就会触发DOMContentLoaded事件

document.addEventListener("DOMContentLoaded", function(event) {
    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";
    mySpan.style.color = "red";
    document.body.appendChild(mySpan);
});

Browser supported : 浏览器支持:

Chrome     Firefox (Gecko)         IE   Opera   Safari

0.2         1.0 (1.7 or earlier)   9.0  9.0     3.1

I usually avoid using frameworks unless absolutely necessary, but in this instance I think you could use jquery: 我通常避免使用框架,除非绝对必要,但在这种情况下,我认为您可以使用jquery:

$(function () {
    // do stuff after DOM has loaded
});

So, wrap your code like so: 因此,将您的代码包装如下:

<script type="text/javascript">
$(function () {
    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);
});
</script>

Remember you will need to reference jQuery 记住,您将需要引用jQuery

This is not the same as window.onload - onload executes after all other resources have been loaded (images etc.) 这与window.onload onload在加载所有其他资源(图像等)之后执行

The code I showed in my example will execute when the DOM has finished loading 我在示例中显示的代码将在DOM完成加载后执行

看起来最快的检测document.body何时可用的方法是使用MutationObserver ,如https://stackoverflow.com/a/26324641/454780所示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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