Dear all

I am loading a number of JavaScript files dynamically by appending to
the <head/> element. To ensure they're added in the correct order I
came up with the following code which uses a PeriodicalExecuter to
step through an array of script names as and when an anticipated
object in each script becomes available.

    function loadScripts() {
        var scripts = [
            { src: 'js/s1.js' , obj: 'Stu.s1.func' },
            { src: 'js/s2.js' , obj: 'Stu.s2.func' },
            { src: 'js/s3.js' , obj: 'Stu.s3.func' }
        ];
        var stoptime = (new Date()).getTime() + 5000;
        var i = 0;
        var scriptadded = false;

        new PeriodicalExecuter(function(pe) {
            if (!scriptadded) {
                addScript(scripts[i].src);
                scriptadded = true;
            }

            if ((window.Stu) && (eval(scripts[i].obj))) {
                // Found an object
                if (i < scripts.length - 1) {
                 // Prepare to load next script
                  i++;
                  scriptadded = false;
                } else {
                  // That was the last script
                  pe.stop();
                  callback_success();
                }
            } else if ((new Date()).getTime() > stoptime) {
                pe.stop();
                callback_outoftime();
            }
        }, 0.2);
    }

File "s1.js" is defined as:

    var Stu = window.Stu || {};
    Stu.s1 = { func: function () { alert('s1'); } };

File "s2.js" is defined as:

    var Stu = window.Stu || {};
    Stu.s2 = { func: function () { alert('s2'); } };

File "s3.js" is defined as:

    var Stu = window.Stu || {};
    Stu.s3 = { func: function () { alert('s3'); } };

The function addScript() is not defined here but was inspired by [1].
The function callback_success() will do something interesting with my
dynamically-loaded functionality ;)

The problem is that it works in IE8, Safari 4 and Chrome 3 but not
Firefox 3.5.7. It breaks when eval'ing the second object, i.e.
"Stu.s2.func". I guess this is something to do with scope, but why
should it work the first time around?

I appreciate this might not be a Prototype issue per se but any advice
would be welcome. I'm currently considering making one long script to
avoid any of these shenanigans.

Thanks
Stuart

[1] http://proto-scripty.wikidot.com/prototype:how-to-load-scripts-dynamically.

-- 
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptacul...@googlegroups.com.
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en.


Reply via email to