如何在< head&gt在< body>的末尾添加脚本 [英] How to have a script in the <head> add script at the end of the <body>

查看:81
本文介绍了如何在< 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 事件:


当文档被完全加载和解析时,DOMContentLoaded事件被触发,而不等待样式表,图像和子帧完成加载(加载事件可用于检测完全加载的页面)。

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 准备好 事件 jQuery

文档

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆