skip to Main Content

I’m trying to load a lazy loader plugin which requires jQuery to function.
If I write my script as such:

require([
        "jquery",
        "ScandiLazy",
    ], function ($) {
        jQuery('.category-products .lazy').lazy();
    });

I get:

"jquery.lazy.min.js:43 Uncaught TypeError: Cannot read property 'fn' of undefined",

Followed by:

Uncaught TypeError: jQuery(...).lazy is not a function

which is an error through because jQuery is not loaded.

But if I nest the requires:

 require([ "jquery"], function ($) {
        require([ "ScandiLazy"], function ($) {
            jQuery('.category-products .lazy').lazy();
        });
    });

Then it works perfectly.

But it feels wrong to nest the requires in order to make it work, is this actually a correct way to do this?

If this is incorrect, what’s a way to make absolute sure jQuery is loaded before the ScandiLazy lazy load plugin loads?

2

Answers


  1. ScandiLazy needs jQuery to work so you have to tell RequireJS to set jQuery as dependency for ScandiLazy using shim (more here https://requirejs.org/docs/api.html#config-shim). Quick example how to fix this:

    requirejs.config({ // configure RequireJS first
        shim: {
            'path/to/ScandiLazy': ['jquery']
        }
    });
    
    require([ // load modules
        "jquery",
        "ScandiLazy",
    ], function ($) {
        jQuery('.category-products .lazy').lazy();
    });
    
    Login or Signup to reply.
  2. I think the correct way in M2 is to add this to requirejs-config.js of your module/theme

    var config = {
        shim: {
            'ScandiLazy': ['jQuery']
        },
        map: {
            ...
        },
    };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search