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 bo
$(document).ready(){}
is executed when your dom element render successfully.
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
As you're waiting for jQuery to load, you can simply wrap your code within jQuery's $(document).ready() method:
$(document).ready(function() {
// Your code here.
});
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside
$( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
I realise that you've mentioned that you want this in "vanilla" JS, but as you're waiting for jQuery to load anyway this seems a bit redundant.
Tell your code to wait for the DOM to finish loading:
window.onload = function() {
var script = document.createElement("script");
script.type = "text/javascript";
//....
}
Or using jQuery:
$(document).ready(function() {
var script = document.createElement("script");
script.type = "text/javascript";
//....
});
When the browser run your code in <head>
, the <body>
element didn't existed yet. So, document.body
was null
.
To create a script a the <body>
element, use 'load' event of document
, for example:
.............
document.addEventListener('load', function(event){
var script = document.createElement('script');
...............
document.body.appendChild(script);
}, false);
............