javascript - 如何在<head>中有一个脚本在<body>末尾添加脚本

标签 javascript jquery dom

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

我尝试过这个:

<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 可用之前)。我唯一能想到的就是设置一个计时器,但这似乎有问题。

有什么建议吗?

最佳答案

使用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
});

DOMContentLoadedready 相同jQuery 的事件。

Documentation

关于javascript - 如何在<head>中有一个脚本在<body>末尾添加脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772994/

相关文章:

javascript - 加快初始加载时间的技巧

javascript - Windows 应用商店应用程序 - 从辅助磁贴启动时执行单个任务

javascript - 如何使用 for 语句和数组确定单击了哪个元素

php - 如何在json中拆分日期和时间?

javascript - 从多个文件上传中检索文件大小

javascript - 井字游戏 : Sqaure cannot be overridden

javascript - document.evaluate 在 chrome 和 firefox 中

javascript - 动态创建的复选框未触发操作

dom - 建议用于构建小部件的最小 Dom 操作库

css - 将 div 标签注入(inject)每个 <a> 链接