I am currently working on developing a page constructor entirely using JavaScript. The issue arises when I dynamically add two scripts to the page that are dependent on each other. For instance, in this scenario, I am loading jQuery from a CDN, and in the second script, I attempt to call a jQuery function to modify the title text. However, since the first script hasn't loaded yet, I encounter the error ReferenceError: $ is not defined
.
What would be the optimal approach in this situation? Should I wait to load the next script until the previous one is fully loaded?
One thing to note is that I prefer not to utilize external libraries like RequireJS, as it would require constant updating whenever the plugin is updated, making it unfeasible in this case.
EXAMPLE
Here are my JS classes:
NS.Script = function(nHasCode, nType, nSrc, nContent){
this.hasCode = nHasCode;
this.src = nSrc;
this.type = nType;
this.content = nContent;
};
NS.Page = function(){
this.id;
this.isIndex;
this.title;
this.metas = [];
this.links = [];
this.styles = [];
this.scripts = [];
this.body;
};
NS.Page.prototype.addScript = function(hasCode, type, src = null, content = null){
var aux = new NS.Script(hasCode, type, src, content);
var pageScripts = this.scripts;
pageScripts.push(aux);
};
NS.Pages = {
load: function(page){
document.body.innerHTML = page.body;
document.title = page.title;
page.scripts.forEach(function(pageScript) {
if(pageScript.hasCode){
document.write("<script type="+pageScript.type+">"+pageScript.content+"<\/script>");
}else{
var s = document.createElement( 'script' );
s.setAttribute( 'type', pageScript.type );
s.setAttribute( 'src', pageScript.src );
if (s.readyState){
script.onreadystatechange = function(){
if (s.readyState == "loaded" ||
s.readyState == "complete"){
s.onreadystatechange = null;
//At this point, I may need to call the script load of each dependency
}
};
} else {
s.onload = function(){
//callback();
//At this point, I may need to call the script load of each dependency
};
}
document.getElementsByTagName("head")[0].appendChild( s );
}
});
}
};
Lastly, I create a new page and add two scripts:
var page = NS.Pages.new("Test", "Page 1");
page.title = "Page title";
page.isIndex = true;
page.body = "<h1 id='title'>Page title with H1</h1><p>This could be a paragraph</p>";
page.addScript(false, 'text/javascript', 'https://code.jquery.com/jquery-2.2.3.min.js');
page.addScript(true, 'text/javascript', null, "$('#title').text('The new title configured with jQuery');");
NS.Pages.load(page);