What is the correct way to dynamically import JavaScript files (.js) into JavaScript source code?
I am using the following code, but this seems to be wrong:
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 wrong, because in the main JavaScript code I cannot read the variables defined in the imported code, for example:
var fileRef = loadjscssfile('Language/svk.js', 'js'); alert("Pet Name: " + PETNAME);
the imported svk.js file contains a single code:
// JavaScript Document var PETNAME = "Beauty";
Thanks.
source share