Magento 2 – window.on ‘load’ Function Not Usable with RequireJS Loaded File

frontendjavascriptjquerymagento2requirejs

I am trying to use $(window).on('load', function(){}); in file that is being pulled into my template with require JS, but no matter how i configure the JS, it will not execute.

The odd part is, this code will execute fine when placed in <script> tags in the phtml, so i know it's not an issue with the JS itself.

In my template file i have this code:

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Cms/js/tester": {}
    }
}
</script>

And i know this is calling in the correct JS file, as i have tested the console.log inside and outside the $(window).on('load', function(){});. When i hit the page, tester 1 always prints, tester 2 does not. Inside the JS file i have:

define([
    'jquery'
], function ($) {
    'use strict';
    console.log('tester 1');
    $(window).on('load', function(){
        console.log('tester 2');
    });
});

If i take this code and put it in the template file itself, it always prints:

<script>
    require([
        'jquery'
    ], function ($) {
        'use strict';
        $(window).on('load', function(){
            console.log('tester 1');
        });
    });
</script>

So the logical conclusion would be that there is an issue with require JS loading in this JS file, but how could i track this down and test to see why this is not loading correctly?

Best Answer

First of all, you have to change your mindset, writing AMD is different than old fashioned adding JS code directly to the template.

Don't wait for load event, because it's pointless in an asynchronous environment, you can't define a certain point where your code will be loaded and executed.

If you need to do an action after another asynchronous call, like a network request, you need to run your code after it finishes and there are few ways to do it:

  • invoke your function in the callback of method you are waiting for
  • dispatch an event and listen to it
  • use promises (ES6)
Related Topic