What is the correct way to dynamically import JavaScript (.js) files into a parent JavaScript code, please?
I am using the following code, but it seems not correct:
function loadjscssfile(filename, filetype)
{
//if filename is a external JavaScript file
if (filetype=="js")
{
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
//if filename is an external CSS file
else if (filetype=="css")
{
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
I think, the code is not correct, because, in the master JavaScript code, I can no read variables defined in the imported code, such as:
var fileRef = loadjscssfile('Language/svk.js', 'js');
alert("Pet Name: " + PETNAME);
imported svk.js file contains the only code:
// JavaScript Document
var PETNAME = "Beauty";
Thank you.
alert("Pet Name: " + PETNAME);
into the imported code, and there it gets run, and I see the alert box with appropriate value. However, if thealert("Pet Name: " + PETNAME);
is moved to the master file, I can not get the value ofPETNAME
– Arrival