2

When I use $.getScript the variables in the main javascript file cannot pass to included js file. For example:

var tVar = 'Hello World!';
$.getScript('js/setting.js', function() {
    // My callback code
});

setting.js:

alert(tVar);

How can I pass variables to included file?

3 Answers 3

2

May be use a function inside your included js file and pass variable as arguement to that function.

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

Comments

1

The loaded script can only access global variables.

You've got two options:

  1. Temporary create a global variable.
  2. Call the injected function from within the callback.

Code for method 1:

var tVar = 'Hello World!';
$.getScript('js/setting.js');
window.get_tVar = function() {
    delete window.get_tVar; // Clean-up
    return tVar;
};
// In settings.js:
function logic() {
    var tVar = window.get_tVar();
}

Code for method 2:

var tVar = 'Hello World!';
$.getScript('js/setting.js', function() {
    newGlobalFunc(tVar);
});

// In settings.js:
function newGlobalFunc(tVar) {
    // Do something
}

Comments

0

Well, to be honest I don't know why more people don't do this, but here's what I do

// settings.js

var com = {};
com.example = {};    

( function( $ ) {

    com.example.Main = function(){
        var private = {};
        var public = {};

        public.initialize = function( myVar ){
            alert( myVar );
        }

        return public;
    }()

})( jQuery );


// main 
var myVar = 'Hello World!';
$.getScript('js/setting.js', function() {
    com.example.Main.initialize( myVar );
});

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.