1

I'm adapting the code from the Stellar HTML5UP template to my needs. At some point I decided to update jQuery from 1.11.7 to 3.1.0.

(function($) {

    $(function() {

        var $window = $(window),
            $body = $('body'),
            $main = $('#main');

        // Disable animations/transitions until the page has loaded.
        $body.addClass('is-loading');

        $window.on('load', function() {
            console.log("Page loaded");
            window.setTimeout(function() {
                $body.removeClass('is-loading');
            }, 100);
        });

        // more code
    });

})(jQuery);

When using jQuery 1.11 I can see "Page loaded" in my web console. After updating jQuery - the code block is not executed anymore.

Why?

marmistrz
  • 5,974
  • 10
  • 42
  • 94

3 Answers3

1

It was deprecated in 1.8 and removed in 3.0. See docs: https://api.jquery.com/load-event/

willywonka
  • 117
  • 5
  • 1
    According to this post, only the `window.load(...)` syntax is deprecated and one should use `window.on('load', ...)` instead: http://stackoverflow.com/questions/12643160/load-method-deprecated – marmistrz Jul 31 '16 at 15:59
  • jquery 3.1.0 still supports .on() function but .laod() is deprecated – jonju Jul 31 '16 at 16:00
  • and I'm using `on`... I don't understand – marmistrz Jul 31 '16 at 16:01
  • 3
    Reading a bit of documentation looks like the load event fires once and you are already detecting it in `(function($) {` so if you check it again, like you do in `$window.on('load', function() {` it won't be detected because it already has fired. That's why the documentation recommends `.ready()` because it actually checks if it has been loaded, – yuriy636 Jul 31 '16 at 16:19
0

Does this suffice your requirement

var $window = $(window),
    $body = $('body'),
    $main = $('#main');       
    $body.addClass('is-loading');
    $(window).on('load', function() {
        console.log("Page loaded");
        window.setTimeout(function() {
            $body.removeClass('is-loading');
        }, 100);
    });

wrap the script inside your body

https://jsfiddle.net/78z2rmsb/

jonju
  • 2,711
  • 1
  • 13
  • 19
  • why does this work and the previous not? You only changed `$window` to `$(window)`. After typing this into the Firefox web console, I get `TypeError: window.on is not a function`. Why did I get no error in the web console when loading the webpage? – marmistrz Jul 31 '16 at 18:52
0

As has already been stated the window load has already occurred by the time ready has been called. Try declaring the window on load outside of the document ready, as below.

<script>    
    $(window).on("load", function() {
        // do something
    });

    $(document).ready(function(){
        // do other stuff
    });
</script>
PCannon
  • 55
  • 4