Laurent-514
Laurent-514

Reputation: 621

Need jQuery opposite to document.ready

I need a function that will trigger some JavaScript code before the page loads. It's the opposite of document.ready

Any ideas?

Thanks!

Laurent

Upvotes: 1

Views: 3403

Answers (4)

Vixed
Vixed

Reputation: 3499

jQuery $.holdReady() method, which holds or releases the execution of jQuery's ready event.

Example:

    $.holdReady(true);
    // your javascript code before the ready event
    $.holdReady(false);

From jQuery documentation

The $.holdReady() method allows the caller to delay jQuery's ready event. This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready. This method must be called early in the document, such as in the <head> immediately after the jQuery script tag. Calling this method after the ready event has already fired will have no effect.

To delay the ready event, first call $.holdReady( true ). When the ready event should be released to execute, call $.holdReady( false ). Note that multiple holds can be put on the ready event, one for each $.holdReady( true ) call. The ready event will not actually fire until all holds have been released with a corresponding number of $.holdReady( false ) calls and the normal document ready conditions are met. (See ready for more information.)

Upvotes: 0

user2033671
user2033671

Reputation:

Nothing is built into jQuery but you can write a plugin to do it. The code just has to be placed at the top of the page

(function($){
    $.fn.notReady = function(func){
         return func();
    }
})(jQuery);

$(document).notReady(function(){
     alert("Hello World!");
});

You could also use the Vanilla JS framework instead of jQuery. It is cross platform and has this feature built in.

Upvotes: 0

Gui
Gui

Reputation: 9823

You can just run the code directly before referencing any other script (if you're not dealing with async tasks it should be ok).

You can have a IOC or boot script to load the libs, it should be easy. In frameworks like AngularJS you've this natively, but check RequireJS for example.

How about using a ServiceWorker? Again, it depends of what you're trying to achieve.

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

<html>
    <head>
       <script type="text/javascript">
              //code here will run when encountered...
              //to ensure jQuery not loaded you can do this:
              if ( typeof jQuery  == undefined ){
                  //jQuery be like not there.
              }
       </script>

        <title>My Page</title>
    </head>
    <body>
    </body>
</html>

Upvotes: 1

Related Questions