Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a script in the <head> add script at the end of the <body>

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?

like image 941
Peter R Avatar asked Apr 21 '15 13:04

Peter R


People also ask

Can I place script tag after body?

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.

Do you put script in head or body?

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.

Can we add script tag in head?

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.

Why is the script tag placed towards the end of the body tag?

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.


1 Answers

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

like image 63
Tushar Avatar answered Sep 28 '22 01:09

Tushar