2

I have the below js. which is also in this fiddle

    (function () {
        var test = document.createElement('script');
        test.type = 'text/javascript';
        test.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.example.com/test.js';
        console.log(test);
        document.getElementsByTagName('body')[0].insertAdjacentHTML("beforeEnd", test);
    })();

I want to put the js at the bottom of my page just before the closing js tags.

When I view it in the console.log I get the expected result. Which is

<script type=​"text/​javascript" src=​"http:​/​/​www.example.com/​test.js">​</script>​

However when I try and actually add it to my page I get [object HTMLScriptElement]

What am I missing here or is there another method I can try to acheive this?

3 Answers 3

4

insertAdjacentHTML takes html as its argument not dom nodes. I'd use appendChild instead

document.getElementsByTagName('body')[0].appendChild(test);
Sign up to request clarification or add additional context in comments.

1 Comment

appendChild also has the benefit of having universal browser support, which isn't the case for insertAdjacentHTML.
2

I took a slightly different approach and tried appending the script as a child of the body node. Here's an example using your code:

(function (document) {
    var test = document.createElement('script');
    test.type = 'text/javascript';
    test.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.example.com/test.js';
    document.getElementsByTagName('body')[0].appendChild(test);
})(document);

It seems to get the desired result.

Hope this helps!

Comments

1

I think 'beforeend' needs to be all lowercase.

[...] document.getElementsByTagName('body')[0].insertAdjacentHTML("beforeend", test);

https://developer.mozilla.org/en-US/docs/Web/API/element.insertAdjacentHTML

Look above for Musa's answer, which is the correct insertion method in this case.

Comments

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.