JavasScript dynamic import

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.

+4
source share
3 answers

The reason you cannot read the PETNAME variable is because the dynamic injections of such scripts are asynchronous and non-blocking. This means that your alert is executed before the script loads. Instead, you may need to PETNAME for the presence of the PETNAME variable:

 var waitForPETNAME = function(){ if (typeof PETNAME === 'undefined') { setTimeout(waitForPETNAME, 15); } else { // execute code that uses PETNAME } }; waitForPETNAME(); 

In addition, a safer way to dynamically input elements is to insert them before the first script element, since you know for sure that the script element must exist (otherwise you will not execute the code), in other words, replace:

 document.getElementsByTagName("head")[0].appendChild(fileref) 

from:

 var insref = document.getElementsByTagName('script')[0]; insref.parentNode.insertBefore(fileref, insref); 
+2
source

You cannot use the variables and functions defined in the external JS file immediately after inserting the <script> . It takes a few milliseconds for the browser to download the file and execute it.

You will need to work with some kind of callback in order to have the correct load order for your JavaScript.

For proper conditional loading of JavaScript, see Require.js . There, an asynchronous module definition template is implemented.

+4
source

In svk.js add the following (after decelerating the variable):

 svkLoaded(); 

In the main code file, add the following:

 function svkLoaded() { alert("Pet Name: " + PETNAME); } 
+3
source

Source: https://habr.com/ru/post/917256/


All Articles