Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  4] [ 6]  / answers: 1 / hits: 20491  / 12 Years ago, sat, june 2, 2012, 12:00:00

Possible Duplicate:

Dynamically Importing JavasScript






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



In the external .js file I define a varialbe such as follows:



// JavaScript Document
var PETNAME = Beauty;


After dynamically importing that code, I wish to access PETNAME variable, but I do not get the defined value:



alert(Pet Name:  + PETNAME);


What can be wrong, and is there a way to bring values from external .js code into the master JavaScript?



Thank you.


More From » web

 Answers
8

To import JS dynamically, you need to consider onreadystatechange and load events which are run 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 like this:



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

[#85187] Friday, June 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;