本文介绍了如何在< head&gt在< body>的末尾添加脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端正在使用Sharetribe,它允许您通过管理员添加自定义JS,但只能在头部。我希望我的脚本在jQuery之后加载,但jQuery加载到正文的末尾。文件加载后,如何编写添加主脚本的vanilla JS?

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?

我尝试过:

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

但在文档加载完成之前(特别是在jQuery可用之前),它会被执行。我唯一可以想到的是设置一个计时器,但是这似乎很麻烦。

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.

任何建议?

推荐答案

使用 DOMContentLoaded 事件:



document.addEventListener("DOMContentLoaded", function (event) {
  console.log("DOM fully loaded and parsed");

  // Your code here
});

DOMContentLoaded 与事件 jQuery

这篇关于如何在&lt; head&gt在&lt; body&gt;的末尾添加脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:25