Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute js when document.body exists

Tags:

javascript

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?

like image 897
Alex Avatar asked Feb 07 '26 14:02

Alex


1 Answers

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
like image 61
Merlin Avatar answered Feb 09 '26 11:02

Merlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!