Add custom javascript to all pages on your theme

Use custom javascript

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

});

Replace javascript functionality

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

Incorporate a javascript library

You can also use this method to incorporate a javascript library into your site to be used whenever needed. In the example below we are incorporating enquire.js javascript library. The requirejs-config.js file would be something like:

var config = {
	paths: {
		'enquire': [
			'https://cdnjs.cloudflare.com/ajax/libs/enquire.js/2.1.6/enquire.min',
			'Magento_Theme/js/enquire'
		]
	},
	shim: {
		'enquire': {
			deps: ['jquery'],
		}
	}
};

Here requirejs will load the enquire.js library from the cdn first. If that is not possible then it will look for the enquire.js library locally in file Theme_Vendor/Theme_Name/Magento_Theme/web/js/enquire.js. Also note the use of the shim configuration to set a dependency on jQuery. This means that requirejs will always load jQuery before enquire because jQuery is necessary for enquire to run properly.

Then this library call be called inside any script tag in your website using:

<script type="text/javascript">
//<![CDATA[
require([
	"jquery","enquire"
], 
function($,enquire) {
	"use strict";

        // CUSTOM CODE HERE
        enquire.<code ...>
});
//]]>
</script>

Leave a Reply

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