首次加载时“$ 未定义”

'$ is not defined' on first load

我正在为工具 (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 第一次可用?

谢谢

尝试使用 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 () {};
});

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

ES5:

You can create your element with an "onload" handler, and that will be called when the script has been loaded and evaluated by the browser.

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() which runs asynchronously. Support is not great - https://caniuse.com/#feat=es6-module-dynamic-import. Here is another link making use of this. I would only recommend using this where BabelJS

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