【问题标题】:How to insert script tag in head of DOM before it is fully loaded?如何在完全加载之前在 DOM 的头部插入脚本标签?
【发布时间】:2023-03-16 17:50:01
【问题描述】:

所以我正在使用 Electron 框架来构建一个应用程序来加载页面并将我自己的脚本注入其中。但是,module 是在全局范围内定义的,因此 jQuery 脚本看不到 window 对象

if ( typeof module === "object" && typeof module.exports === "object" ) {
  // set jQuery in `module`
} else {
  // set jQuery in `window`
}

发生这种情况是因为我希望我的注入脚本运行的节点集成已打开。因此,问题是客户端脚本无法正常工作,我看到类似

的错误
Uncaught ReferenceError: jQuery is not defined
custom.min.js:1 Uncaught ReferenceError: jQuery is not defined
homeOffer.min.js:1 Uncaught ReferenceError: $ is not defined
main.js:48 Uncaught ReferenceError: $ is not defined

如果我在客户端页面上的任何脚本运行之前设置window.module = undefined,那么它可以正常工作。

我想通过插入一个脚本标签来修改 DOM,该标签将在任何脚本运行之前将 module 设置为 undefined

我有一个document 对象的句柄,我尝试了下面的

document.addEventListener("DOMContentLoaded", function(event) {
    var s = document.createElement("script");
    s.innerHTML = "console.log('hello from script'); window.module = undefined;";
    document.head.insertBefore(s, document.head.childNodes[0]);
    console.log('dom loaded');
});

但是,如果在解析 DOM 并且所有脚本都已运行时触发事件 DOMContentLoaded,则问题是它无法达到目的。

我的问题是可以在任何脚本在客户端页面上运行之前运行我的脚本标签吗?

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    尝试:

    1. 创建像 /script1.js 这样的脚本文件

    2. 使用这行脚本添加:

      var jq = document.createElement('script');

      jq.src = "http://www.example.com/script1.js";

      document.getElementsByTagName('head')[0].appendChild(jq);

      jQuery.noConflict();

    就像我添加 jquery 脚本:

    var jq = document.createElement('script');
    jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(jq);
    // ... give time for script to load, then type (or see below for non wait option)
    jQuery.noConflict();
    

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多