Add custom javascript to all pages on your theme

The best solution to add custom javascript to all pages of your website is to create a javascript module and load it via requireJS.

This can be done by creating a requirejs-config.js file in your theme folder with the following content:

# File Theme_Vendor/Theme_Name/requirejs-config.js

var config = {
	deps: [
		"js/custom"
	]
};

This file tells requireJS to load a custom.js file located in folder Theme_Vendor/Theme_Name/web/js. Include in that file the custom javascript you want to run on all pages of your site. Example:

# File Theme_Vendor/Theme_Name/web/js/custom.js

define([
	"jquery"
], 
function($) {
	"use strict";

        // CUSTOM CODE HERE

});

This type of approach should also be used if you want to replace existing javascript functionality. For that you should use map instead of deps in your requireJS file. The content would be something like:

# File Theme_Vendor/Theme_Name/requirejs-config.js

var config = {
    config: {
        mixins: {
            'mage/dropdown': {
                'js/custom-dropdown': true
            }
        }
    }
};

This would replace the dropdown.js file with file custom-dropdown.js located under Theme_Vendor/Theme_Name/web/js

Leave a Reply

Your email address will not be published. Required fields are marked *