views:

50

answers:

3

Hi guys,

I can't seem to get the following functionality to work under Chrome and Opera (latest versions on Windows XP). The code is:

$.getScript('/js/modules/'+module+'.js', function() {
    setTimeout('window.'+module+'_init()', 800);
});

Everything seems to work fine, the script loads, init function exists (a few debug alerts within that setTimeout statement verified that type of "window.module_init" really is a function) but the function just won't run.

I tried putting a simple alert at the beginning of that init function, leave ONLY an alert there - nothing helped.

I must say I'm quite puzzled by this, as this works just fine under Firefox and MSIE.

FYI, the init function in that external js file simply looks like this:

function notifications_init() {
    alert('test');
}

"notifications" is the value of my "module" variable above

Any advice is greatly appreciated :-)

A: 

How about setTimeout('window.'+module+'_init', 800);, without the braces?

tdammers
+1  A: 
setTimeout(window[module+'_init'], 800);
epascarello
that solved it, thanx... one question however - should I be using window as an array instead of using "window.variable" to access a variable defined in this fashion: var abc = 1
Smejko
You aren't using window as an array, its just a different notation...http://www.javascripttoolbox.com/bestpractices/#squarebracket
Ravindra Sane
ah, I see... thanks!
Smejko
A: 

I've just tested what you are explaining here and it worked great here. I am guessing that the external js file that you are loading using $.getScript contains errors.

Could you comment everything inside that file except for the notifications_init() you have in your question?

This is what I did:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
    $(document).ready(function () {
        alert('start');
        var module = 'test';
        $.getScript('/Scripts/' + module + '.js', function () {
            alert('script was loaded and executed');
            setTimeout('window.' + module + '_init()', 800);
        });
        alert('finish');
    });
</script>

And test.js contains only this:

function test_init() {
    alert('test function');
}
Peter