Reputation: 8072
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?
Upvotes: 3
Views: 2909
Reputation: 45484
Looks like the fastest way to detect when document.body
is available is with MutationObserver
, as seen in https://stackoverflow.com/a/26324641/454780
Upvotes: 0
Reputation: 4917
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
Upvotes: 3
Reputation: 38529
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
Upvotes: 1