Mixing window.onload and jQuery $ (function () {})

Is it possible to mix window.onload and $ (function () {}); jQuery in the same script?

    <script type="text/javascript">
        this.onload = function () {
            // do something
        }

        $(function () {
            //do something
        });
    </script>
+4
source share
4 answers

it is perfectly acceptable to do what you asked for:

// check when DOM is ready
$(function(){
    // place code here 
    console.log('DOM ready');
});

// check when all images, links and assets have been loaded
window.load = function(){
      // place code here 
      console.log('window loaded');
};

you can also do this to make sure the DOM is ready before checking for a load event

// check when DOM is ready
$(function(){       
      // check when all images, links and assets have been loaded
      $(window).on('load',function(){
           // place code here 
           console.log('window loaded');
      });
      console.log('DOM ready');
});

or with native javascript for the window.load event

// check when DOM is ready
$(function(){
      // check when all images, links and assets have been loaded
      window.load = function(){
          // place code here 
          console.log('window loaded');
      };
      console.log('DOM ready');
});

Even the jQuery API docs ready () says it's ok: http://api.jquery.com/ready/

You can do this to make sure the DOM is ready before checking the window.load event. It may be posted out yes, but sometimes due to various browser inconsistencies and loading other scripts.

window.load, , , window.load , DOM , .

jQuery ready, , . ready() window.load , , .. .

0

, $(function () { // ... }) - $(document).ready(), , DOM /, window.onload , , $(function () { // ... }) , onload .

$(function () {
    console.log('reday event'); // this will fire at first
});

this.onload = function () {
    console.log('load event'); // this/second will fire after "ready" event
}

, , window.onload jQuery load , .. $( window ).load(function() { // ... }).

, ( , ready, onload).

0

You mean window.onload = function () { };, which will be launched after downloading all the images, etc.

$(function () { });or it $(document).ready(function () { });starts after the DOM has been successfully created, and therefore, when you can be sure, you can select any / specific elements.

0
source

I'm not sure why you, how they do basically the same thing, so there should be no problem.

-1
source

All Articles