I have some script in document HEAD section like this.
<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. 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.
And important one: i need do this before window will be loading (i mean window.load event).
Can I do this?
If you don't want to use Jquery
you can use DOMContentLoaded
see reference here
The DOMContentLoaded
event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading
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:
$(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
This is not the same as window.onload
- onload
executes after all other resources have been loaded (images etc.)
The code I showed in my example will execute when the DOM has finished loading
看起来最快的检测document.body
何时可用的方法是使用MutationObserver
,如https://stackoverflow.com/a/26324641/454780所示
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.