Reputation: 4264
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?
Upvotes: 2
Views: 95
Reputation: 1319
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!
Upvotes: 2
Reputation: 97717
insertAdjacentHTML
takes html as its argument not dom nodes. I'd use appendChild instead
document.getElementsByTagName('body')[0].appendChild(test);
Upvotes: 4
Reputation: 13354
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.
Upvotes: 1