I am writing up a ContentScript for a Chrome Extension. In the script, I want to import a javascript (actually a JS and a CSS) and initiate a class from that script.
To ensure the Javascript is properly loaded, I followed the guidance from several SO posts like this, this and this.
var link = document.createElement( "link" );
document.body.appendChild(link);
link.onload = function(){
console.log("link loaded");
var script = document.createElement('script');
document.body.appendChild(script); //or something of the likes
script.onload = function () {
...
console.log("script loaded");
// somehow ContentTools is undefined even after the script is loaded
editor = ContentTools.EditorApp.get();
editor.init('*[data-editable]', 'data-name');
console.log("all finished")
};
script.src = "https://....min.js";
};
link.href = "https://....min.css";
link.type = "text/css";
link.rel = "stylesheet";
I am assuming that this way of callling ContentTools.Editor at the innermost of the nested onload is a good way of guarantee that the proper CSS and JS dependencies are properly loaded. However, when I run it as a Chrome Extension inside the contentscript, it errors out with Undefined ContentTools as referenceerror but I saw message "link loaded" and "script loaded".
Clearly, ContentTools are loaded and defined (see the screenshot). And if I execute the whole script directly in the console, everything works. Looks like the root cause is only in Chrome Extension content script, somehow the editor = ContentTools...
got called before the script is fully loaded.
As it is only an error as a Chrome extension but not in the Console, I am a bit lost here. jQuery related solution is also welcome here.