Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  34] [ 1]  / answers: 1 / hits: 5718  / 9 Years ago, tue, april 21, 2015, 12:00:00

A client is using Sharetribe which allows you add custom JS via admin, but only in the head. I want my script to load after jQuery, but jQuery is loaded at the end of the body. How can I write vanilla JS that adds my main script to the end once the doc loads?



I tried this:



<script>
var script = document.createElement(script);
script.type = text/javascript;
script.src = http://cdn...;
document.body.appendChild(script);

var script2 = document.createElement(script);
script2.type = text/javascript;
script2.text = $(SOME.CODE.HERE);
document.body.appendChild(script2);
</script>


But it gets executed before the document is finished loading (and in particular, before jQuery is available). The only thing I can think of is to set a timer, but that seems buggy.



Any advice?


More From » jquery

 Answers
2

Use DOMContentLoaded event:




The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).




document.addEventListener(DOMContentLoaded, function (event) {
console.log(DOM fully loaded and parsed);

// Your code here
});


DOMContentLoaded is same as ready event of jQuery.



Documentation


[#37754] Monday, April 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sageallenv

Total Points: 458
Total Questions: 102
Total Answers: 104

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;