问题描述
我正在为工具(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第一次可用?
谢谢
1楼
Lawless
1
已采纳
2019-03-03 16:45:51
可能重复-document.createElement
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,否则可以使用异步运行的 。 支持不是很好 。 这是利用此 。 我只建议在使用的地方使用它。
import('./jquery.min.js').then((jquery) => {
window.jQuery = jquery;
window.$ = jquery;
// The rest of your code
});
2楼
Bear Nithi
0
2019-03-03 16:40:54
尝试使用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 () {};
});