JavaScript: access to variables defined in external .js files

Possible duplicate:
JavasScript dynamic import

Is there a way to access variables that come from external imported JavaScript.js files?

In an external .js file, I define varialbe as follows:

// JavaScript Document var PETNAME = "Beauty"; 

After dynamically importing this code, I want to access the PETNAME variable, but I do not get a specific value:

 alert("Pet Name: " + PETNAME); 

What could be wrong, and is there a way to bring values ​​from external .js code to main JavaScript?

Thanks.

+6
source share
2 answers

To import JS dynamically, you need to consider the onreadystatechange and load events that fire when the script is parsed by the browser and available to you. You can use this function:

 function getScript(url, callback) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; script.onreadystatechange = callback; script.onload = callback; document.getElementsByTagName('head')[0].appendChild(script); } 

And you can use it as follows:

 getScript('path to your js file', function(){ alert("Pet Name: " + PETNAME); }); 
+10
source

Before attempting to access the variable defined in it, make sure that you include the external file. Also make sure that the variable in the external file is not defined inside the function, in which case they are limited only to this function. If this does not help remove the var keyword before the variable, it will create a global variable.

+2
source

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


All Articles