javascriptjquerydocument-readyyepnopeasynchronous-loader

How can I use yepnope.js with $(document).ready() effectively?


I have been implementing the yepnope script loader as part of the modernizr.js library. I have successfully got jQuery to load and jQuery dependent scripts afterwards. I am new to asynchronous loading of resources, so it's a bit new to me. I have been searching around, but haven't had much luck with the following.

My question is what are your opinions on how to effectively replace the functionality of $(document).ready() when working with the yepnope.js framework.

My theory was to create a appropriately named function in my base library and then set that variable on my pages to an anonymous function containing my existing $(document).ready() code. This variable would then be called by yepnope after all the scripts had loaded in the complete callback.

Would you agree that this is a good way of doing it, or am I approaching this entirely the wrong way?

(For those unaware, the asynchronous nature of yepnope.js means that the document calls $ or jQuery before the yepnope loader has finished, throwing a "$ is undefined" error <- please correct me if that is wrong.)

First question, hope it's a good one.


Solution

  • If load jQuery without yepnope isn't a problem for you, there is a easier way to do.

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    
    <script>
        $.holdReady(true);
    
        yepnope.load({
            load: [
                'placeholder.js',
                'jquery-ui.min.js'
            ],
            complete: function (){
                $.holdReady(false);
            }
        });
    </script>