Magento 2 JS libraries sometimes don't load

2.5k views Asked by At

We are currently running a Magento 2.2.6 instance. Sometimes the product gallery breaks with a JS error:

Uncaught TypeError: settings.$elementF.fotorama is not a function

This also happens to other js libraries on the homepage and catalog page. Sometimes we get an error

Uncaught TypeError: $(...).CustomMenu is not a function

IF you hard-refresh/clear your browser cache it works and all the errors disappear for that page, but if you browse the site it will throw the errors again after visiting a few pages.

I have already tried re-deploying the static assets, turning on and off static signing, disabling all extension, disabling all backend caches and changing my requirejs-config.js file to depend and shim jquery

var config = {
    deps: ['jquery'],
    map: {
        '*' : {
            'hello' : 'js/custom'
        }
    },
    'fotorama/fotorama': {
        deps: ['jquery']
    }
}

This issue has been posted various times before, any advice would be greatly appreciated.

1

There are 1 answers

1
giolliano sulit On

Unfortunately, the dependencies array is not guaranteed to load in order.

You can use a shim within requireJS that will let you define dependencies between libraries and export global variables that can be used with other libraries.

Essentially within the shim, you can use the deps property to define libraries that should be loaded before using the included library.

What you have now is close, but it's not within a shim

Try this:

var config = {
    deps: ['jquery'],
    map: {
        '*' : {
            'hello' : 'js/custom'
        }
    },
    shim: {
        // export the variable 
        jquery: {
            exports: '$'
        },
        // fotorama depends on jquery
        'fotorama/fotorama': {
            deps: ['jquery']
        }
    }
}