1

I want to add one js file at the bottom of the page before </body> tag.

I am trying one format. But its not working properly.

My code

var url = 'sample.js';
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName('body')[0].appendChild(script);

But its not working.

Now i check

var x = document.getElementsByTagName('body');
alert(x.length);

its shows 0

How can i add this js file into my bottom of the page. Please advise

11
  • Your code works as it should. Check here: jsfiddle.net/CUpuq, you can check the console also, the script is there. So, what else can it be not working? what are you trying to do besides this code? Commented Aug 5, 2013 at 7:23
  • Wait i can send a link to you. Commented Aug 5, 2013 at 7:27
  • demo.osiztechnologies.com/demo/tooltip/demo2.html @Sergio please see the link and console. Commented Aug 5, 2013 at 7:36
  • i don't understand and i am confused. any mistake in my code please advise Commented Aug 5, 2013 at 7:39
  • Try var htmlElement = document.getElementsByTagName('body')[0]; without appendChild and then htmlElement.appendChild(script); and then alert(htmlElement.length); Commented Aug 5, 2013 at 7:42

2 Answers 2

1

See this code

var body = document.body;
alert("Body when page loading: " + body);
document.addEventListener("DOMContentLoaded", function() {
    var bodyLoaded = document.body;
    alert("Body when page loaded: " + bodyLoaded);
    var url = "http://code.jquery.com/jquery-1.10.2.min.js";
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = url;
    script.onload = function(){
        var testP = $("<p></p>");
        testP.html("JQuery worked");
        $(document.body).append(testP);
    }
    bodyLoaded.appendChild(script);
});  

If first alert you get null. But in second (when body loaded) you get HTMLBodyElement. This is your mistake if you try to append element to body in head before body loaded.

Sign up to request clarification or add additional context in comments.

Comments

0

You are writing your this code in the head section and at the time this executes body element is not yet created. This is the only reason for error. Keep this code after body element is created.

2 Comments

but i need to run this script only head section. because i am creating firefox addon. so only i need this method
I am not sure about your requirement. If you want to write this code only in head section you can add (append ) your this script in head instead of in body??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.