5

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.

Community
  • 1
  • 1
Bunkai.Satori
  • 4,698
  • 13
  • 49
  • 77

2 Answers2

12

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);
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • +1 - Thank you for the answer. You correctly got the source of my problem, that I do import the .js file dynamically. I will use the advices presented. As your answer is clear and requires no further additions, I would like to mark it as the *Accepted Answer* for my question. – Bunkai.Satori Jun 02 '12 at 18:29
  • @Bunkai.Satori: Glad to see that it helped :) – Sarfraz Jun 02 '12 at 18:29
3

Make sure you are including external file before trying to access variable defined in it. Also make sure the variable in the external file is not defined inside function, in which case they range is limited to that function only. If this not helps try removing keyword var before variable, this will create global variable.

Zefiryn
  • 2,240
  • 2
  • 20
  • 30
  • +1, thank you very much for your answer. Removing `var` was new to me. Moreover, I should have mentioned, that I am dynamically importing the .js code. I did not know, it is crucial to the answer. Thank you. – Bunkai.Satori Jun 02 '12 at 18:26
  • 1
    Removing var keyword is extremely bad practice, it creates global variables and pollutes the global environment. – Sarfraz Jun 02 '12 at 18:28
  • @Sarfraz, is there any other way to ensure the variable will be global? In other words, is there any better alternative to removing `var`? – Bunkai.Satori Jun 02 '12 at 18:30
  • @Bunkai.Satori: One can use self-invoking anonymous function or the singleton/module pattern: http://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/ but it wont work in your case since you are importing a js file directly. – Sarfraz Jun 02 '12 at 18:33