0

I'm writing a html plugin for a tool(sonarqube). In this I need to write code in below fashion by first registering a extension.

While running the code, I'm facing: ReferenceError: $ is not defined

Code:

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 () {};

});

It works when I load the plugin second time, but not the first time. Any suggestion, how can I make sure jquery is available the first time?

Thanks you

reiley
  • 3,759
  • 12
  • 58
  • 114
  • 2
    Possible duplicate of [Uncaught ReferenceError: $ is not defined?](https://stackoverflow.com/questions/2075337/uncaught-referenceerror-is-not-defined) – zmag Mar 03 '19 at 16:36
  • 3
    ^I don't think this is a duplicate at all, technically very different compared to the one you mentioned. @zmag – Imdad Mar 03 '19 at 16:37

2 Answers2

1

Possible duplication of - 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);

EDIT 1:

ES6:

The above is the best solution, unless you're prepared to host jQuery locally then you could use 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 is used.

import('./jquery.min.js').then((jquery) => {
  window.jQuery = jquery;
  window.$ = jquery;
  // The rest of your code
});
jaredrethman
  • 512
  • 5
  • 16
0

Try using 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 () {};
});
Nithya Rajan
  • 4,722
  • 19
  • 30