简体   繁体   中英

Script in head section to create a DIV in the body

I have to place a script in the head that creates a DIV element and inserts this DIV into the body tag.

var condiv = document.createElement("div");
(condiv.innerHTML = " "),
    condiv.setAttribute("class", "ads"),
    document.body.appendChild(condiv),
    0 === condiv.offsetHeight ||
        (function () {

        }

The script works when I insert it into the body but not before. Is there a way to add the DIV into the body when the script is located into the head (before) with pure javascript and not Jquery? Its very important to have it in the head, because I have to place it before other scripts in the head and I dont want to have this scripts in the body. I know, I could use document.head.appendChild but HTML elements in the head are not validate. Thank you for your time.

Since the script is in the head section and is loaded before the body tag is created you won't find the body tag to place a DIV in it. There are multiple ways you can wrap your script so that it would run after the DOM is loaded. Each with a nuance difference to it. You can see examples of them at MDN . Basically, you can load this code by writing it in this function and it would load after all the page is loaded (including images and other scripts):

window.addEventListener('load', (event) => {
   var condiv = document.createElement("div");
   (condiv.innerHTML = " "),
      condiv.setAttribute("class", "ads"),
      document.body.appendChild(condiv),
      0 === condiv.offsetHeight ||
          (function () {

          }
});

there are ways to load it after only the DOM is loaded that are elaborated in this question I think the answers over there would be even better for your use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM