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?
The <script> Tag You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
If your is not placed inside a function, or if your script writes page content, it should be placed in the body section. It is a good idea to place scripts at the bottom of the <body> element. This can improve page load, because script compilation can slow down the display.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.
The script tag should either be included between the <head> tags or just before the closing <body> tag in your HTML document. JavaScript is often placed before the closing body tag to help reduce the page loading time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With