【问题标题】:'$ is not defined' on first load第一次加载时“$ 未定义”
【发布时间】:2019-07-25 01:10:54
【问题描述】:

我正在为一个工具(sonarqube)编写一个 html 插件。 在这种情况下,我需要先注册一个扩展,以下面的方式编写代码。

在运行代码时,我面临: ReferenceError: $ is not defined

代码:

window.registerExtension('CustomPlugin/muPlugin', function (options) {

    script = document.createElement('script');
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    document.head.appendChild(script);

    var pluginContainer = document.createElement('div');
    pluginContainer.setAttribute("id", "pluginContainer");
    options.el.appendChild(pluginContainer)
    $("#pluginContainer").load("/static/CustomPlugin/customPluginWebPage.html");  // Facing error on this line.

    return function () {};

});

当我第二次加载插件时它可以工作,但不是第一次。 有什么建议,我怎样才能确保 jquery 第一次可用?

谢谢你

【问题讨论】:

标签: javascript sonarqube


【解决方案1】:

尝试使用setTimeOut()

window.registerExtension('CustomPlugin/muPlugin', function (options) {

script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
document.head.appendChild(script);

var pluginContainer = document.createElement('div');
pluginContainer.setAttribute("id", "pluginContainer");
options.el.appendChild(pluginContainer);
setTimeout(() => {
  $("#pluginContainer").load("/static/CustomPlugin/customPluginWebPage.html"); 
}, 2000);


return function () {};
});

【讨论】:

    【解决方案2】:

    可能重复 - document.createElement(“script”) synchronously

    ES5:

    您可以使用“onload”处理程序创建您的元素,当浏览器加载和评估脚本时将调用该处理程序。

    script = document.createElement('script');
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    //Bind a onload handler
    script.onload = () => {
      console.log($);
    };
    document.head.appendChild(script);

    编辑 1:

    ES6:

    以上是最好的解决方案,除非您准备在本地托管 jQuery,否则您可以使用异步运行的 dynamic import()。支持不是很好 - https://caniuse.com/#feat=es6-module-dynamic-import。这是another link 利用它。我只建议在使用BabelJS 的地方使用它。

    import('./jquery.min.js').then((jquery) => {
      window.jQuery = jquery;
      window.$ = jquery;
      // The rest of your code
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      相关资源
      最近更新 更多