Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Accessing Variables Defined in External .js Files [duplicate]

Tags:

javascript

web

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.

like image 275
Bunkai.Satori Avatar asked Jun 02 '12 18:06

Bunkai.Satori


People also ask

What is more appropriate way to include JavaScript as an external file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I copy a variable from one JavaScript file to another?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.

Can we use variable of one JS file to another?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

Can external JavaScript files be cached?

Yes it will cache it. So use timestamp or the updated version in the url via query string. When does browser automatically clear cache of external JavaScript file?


1 Answers

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);
});
like image 61
Sarfraz Avatar answered Sep 27 '22 17:09

Sarfraz