【问题标题】:How to have a script in the <head> add script at the end of the <body>如何在 <head> 中有一个脚本在 <body> 的末尾添加脚本
【发布时间】:2015-04-21 13:01:49
【问题描述】:

一个客户端正在使用 Sharetribe,它允许您通过管理员添加自定义 JS,但仅限于头部。我希望我的脚本在 jQuery 之后加载,但 jQuery 是在正文的末尾加载的。文档加载后,如何编写将我的主脚本添加到末尾的 vanilla 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 可用之前)。我唯一能想到的就是设置一个计时器,但这似乎有问题。

有什么建议吗?

【问题讨论】:

  • 你不能把你的代码包装在 window.onload 中吗?

标签: javascript jquery dom


【解决方案1】:

使用DOMContentLoaded事件:

DOMContentLoaded 事件在文档完全加载和解析后触发,无需等待样式表、图像和子框架完成加载(加载事件可用于检测完全加载的页面)。

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

  // Your code here
});

DOMContentLoadedjQueryready 事件相同。

Documentation

【讨论】:

  • 对于任何有疑问的读者:最佳做法是不要等待页面加载包含一些额外的脚本,您应该将此脚本包装在 DOMContentLoaded 侦听器中并最初加载它。
【解决方案2】:

告诉你的代码等待 DOM 完成加载:

window.onload = function() {        
    var script   = document.createElement("script");
    script.type  = "text/javascript";
    //....
}

或者使用 jQuery:

$(document).ready(function() {
    var script   = document.createElement("script");
    script.type  = "text/javascript";
    //....
});

【讨论】:

    【解决方案3】:

    当您等待 jQuery 加载时,您可以简单地将代码包装在 jQuery 的 $(document).ready() method 中:

    $(document).ready(function() {
        // Your code here.
    });
    

    在文档“准备就绪”之前,无法安全地操作页面。 jQuery 会为您检测到这种准备状态。 $( document ).ready() 中包含的代码只会在页面文档对象模型 (DOM) 准备好执行 JavaScript 代码时运行。

    我知道您已经提到您希望在“vanilla”JS 中使用它,但是当您等待 jQuery 加载时,这似乎有点多余。

    【讨论】:

    • @Tushar 我确实读过,但如果 OP 无论如何都在等待 jQuery 加载似乎毫无意义。你也可以使用 jQuery 已经提供的代码。
    • @JamesDonnelly 我得到“Uncaught ReferenceError: $ is not defined”,因为 jQuery 是在页面末尾添加的。
    • @PeterR 您需要将该代码 after 添加到您的 jQuery 文件之后(在它之后的 head 元素中 - 它正在被加载的位置 - 或任何地方在您文档的body)。
    • @JamesDonnelly 我明白,这就是我的问题的重点。 CMS 迫使我将自定义代码放在首位。 CMS 默认在正文末尾添加 jQuery。因此我的问题。
    • 彼得,您的问题中没有具体细节;如果我们没有被告知直到文档末尾才加载 JQuery,James 的解决方案看起来非常合理。我现在已将其添加到问题中。
    【解决方案4】:

    当浏览器在&lt;head&gt; 中运行您的代码时,&lt;body&gt; 元素还不存在。所以,document.bodynull

    要创建&lt;body&gt; 元素的脚本,请使用document 的“加载”事件,例如:

    .............
    document.addEventListener('load', function(event){
       var script = document.createElement('script');
       ...............
       document.body.appendChild(script);
    }, false);
    ............
    

    【讨论】:

      【解决方案5】:

      $(document).ready(){} 在你的 dom 元素渲染成功时执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        相关资源
        最近更新 更多