views:

118

answers:

3

Hello,

i execute a javascript with jQuery $.getScript. In the executed script i haven't access to the functions and variables of my source file.

Is there a solution?

A: 

The script executed by $.getScript() does have access to the global context. You can use any global variable (or function for that matter) from within your external script.

Philippe Leybaert
A: 

Thanks, but what's wrong?

first file:

$(function(){
    var test = 'Hello World';

    $.getScript('test.js', function(){
        // do nothing
    });   
}

test.js:

alert(test);

No alert()!

TorbenL
`test` is not in the *global* context here, it's inside your `document.ready` handler, if that script *started* with `var test = 'Hello World';`, it should work.
Nick Craver
+1  A: 

Nick Craver, I just spend 3 (!) hours obsessing over why my thing wouldn't work, and you gave me the insight I needed to make it work.

XOXOXOXOXOXOXOXO

interesting to note:

you can declare a variable as a jquery var like this:

$variableName = something;

That way jquery also has access to it from anywhere in the scope.

$(function(){ 
    $alertString = 'Hello World'; 

    $.getScript('test.js', function(){ 
        // do nothing 
    });    
} 

test.js: 

alert( $alertString ); 
tim
That is quite useful and interesting to know.
Andrew Weir