Question

i use lab.js 2.0.3 for parallel loading my scripts. the problem is, that in 1 of 10 times the "$(window).load" part fired much too early. the part with "$(document).ready" works fine.

example:

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<script src="http://cdnjs.cloudflare.com/ajax/libs/labjs/2.0.3/LAB.min.js" type="text/javascript"></script>

<script>
    $LAB
        .script("script1.js")
        .script("script2.js")
        .script("script3.js")

        .wait(function(){

            $(window).load(function() {
                // Function 1
                $("jQuery Function 1");
                // Function 2
                $("jQuery Function 2");
            });

            $(document).ready(function() {
                // Function 3
                $("jQuery Function 3");
                // Function 4
                $("jQuery Function 4");
            });

        });
</script>

i guess, that i do something wrong, but don't know what : (

Was it helpful?

Solution

This may be because $(window).load() only ever fires once per page. If you missed it waiting on the scripts to load, you missed it. So, between .wait and .load, you have a race condition that's not really predictable whether you'll win or lose.

$(document).ready(), on the other hand, is similar to Deferred Objects in that new callbacks can be added after the event has fired and will still be called.

You can see this demonstrated here: http://jsfiddle.net/coiscir/AFszS/1/

$(window).load(function () {
    console.log('outer window.load');

    // bind after the event
    setTimeout(function () {
        $(window).load(function () {
            console.log('inner window.load'); // you'll never see this
        });
    }, 10);
});

If you want a similar effect as .ready for .load, you can use a Deferred Object to mediate between the actual event and your callbacks: http://jsfiddle.net/coiscir/m4D46/

var windowLoad = $.Deferred();

$(window).load(windowLoad.resolve);

$LAB
    .script("script1.js")
    .script("script2.js")
    .script("script3.js")

    .wait(function(){

        windowLoad.done(function() {
            // Function 1
            $("jQuery Function 1");
            // Function 2
            $("jQuery Function 2");
        });

        $(document).ready(function() {
            // Function 3
            $("jQuery Function 3");
            // Function 4
            $("jQuery Function 4");
        });

    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top