简体   繁体   中英

$(window).on(“load”,fn) not working

I'm using jQuery to check if the website resources are loaded properly. To test if it works I put into the index.html a wrong CSS file.

If I put the following code in the Javascript file , that is included in the head, the message "CSS missing" doesn't appear.

$(window).on("load",function () {
   console.log("loaded")
   $("link").on("error",function(){
      console.log("CSS missing");
   });
});

Instead, if I put the following code at the end of the body in the index.html, the message loading error is printed

<script>
    $("link").on("error",function(){
        console.log("loading error");
    });
</script>

I need the Javascript file working, what I'm doing wrong?

NOTE : Using $(document).ready(fn) also not work.

I can't include the javascript at the end of the body because the same script also monitors the page loading time. I need something that is executed at the end of the body with the javascript included in the head.


SOLUTION without jQuery: I used document.addEventListener('DOMContentLoaded', fn()) instead of $(document).ready(fn) and now all it's working properly. Why? I don't know.

Loading error appears because the code is executed during the parsing of file, but the file might not be downloaded yet. Try using instead:

$(document).ready(function(){

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM