4

Is it possible to send a variable to the script loaded using $.getScript?

At the moment I have:

$.getScript( "js/my_script.js", function() {
// do something here after script has loaded
});

But I want to send a variable to the loaded script. Is this possible, if yes, how?

For example

// this is a variable set outside of the script loaded via `$.getScript`
var my_variable = 1

// how do I get that variable sent to `my_script.js`
$.getScript( "my_script.js", function() {
// do something here after script has loaded
});
1
  • If $.getScript doesn't support parameters/variables, you could try using $_GET variable like: $.getScript( "js/my_script.js?my_variable=1",... Don't know if it works but it's worth a try. Commented Nov 15, 2012 at 11:08

3 Answers 3

10

jQuery.getScript():

The script is executed in the global context, so it can refer to other variables and use jQuery functions.

From the documentation, it seems that your variable should be accessible within a $.getScript(function(){..}) call. Therefore, this is likely a problem with scope. Your variable my_variable exists (presumably) inside $(document).ready(function(){...}), and is therefore restricted to that particular scope.

Try using a global variable by assigning your data to the window object:

// Set it as a global variable by assigning it to the window object
window.my_variable = 'some value';

// Now use it inside of $.getScript()
$.getScript( "my_script.js", function() {
  // Access it by name
  alert(my_variable);
  // or as a property of window
  alert(window.my_variable);
  // both ways to access my_variable work and are valid.
}

Sources: old question here and $.getScript docs here.
Verified on my personal server.

Sign up to request clarification or add additional context in comments.

2 Comments

Just tried it an it worked nicely. The problem was exactly what you said, i.e. the variable was in the $(document).ready(function(){...}). Moved it outside and it started working! Thanks.
Thank you, I did not realize the ready function has a different scope than the window, but hearing someone say it, it just makes sense.
3

You can put your included file into function, then run

    $.getScript(url, function() {
       functionName(params);
    });

Comments

0

Be careful here - javascript is all about thinking 4th-dimensionally (Marty!). $.getScript is asynchronous, so the call will return right away before the script is loaded, potentially. If you have multiple scripts to load and needed to pass something to each of them, you'd have to use different variables because of this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.