Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...