Add Custom JS in Magento 2

After creating a custom theme, developers will look at how to add custom JS in Magento 2.

Within Magento 1, in your custom theme you could specify a local.xml layout file that contained all of layout updates.

Within this file, you could add JS files using the following code snippet.

<?xml version="1.0"?>
        <reference name="head">
            <action method="addItem">

The code above assumes your JS file would be located in Magento’s skin directory and then within your theme folder.

If you’ve managed to create a Magento 2 theme, then you’re ready to add additional JS files to your theme.

Note that the recommendation is to add JavaScript using RequireJS within Magento, however this post will just show you simply how to define a file within the layout XML.

Many of the layout updates required to add JavaScript files will use your theme’s default_head_blocks.xml layout file. As the name suggests, it is the file used to add layout updates to the default head block.

This layout file resides in the Magento_Theme directory within the Magento’s blank and luma themes’ directory.

Within your own custom theme, you can add a similar folder structure:


Then add a default_head_blocks.xml file and add the JS file in the layout configuration.

<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/Module/etc/module.xsd">
        <script src="js/custom.js" />

The JS file should then be added in the following directory.


You may notice that Magento 2’s JavaScript files will be requested from the pub/static folder. If you are running the Magento application in developer mode, then Magento will add these files from your theme’s directory to pub/static. If you’re running Magento in production mode, then after adding a custom JS file, the static files will need to be regenerated.

Clear the original static files within the pub/static and run the following command from within your Magento project’s root directory:

$ php bin/magento setup:static-content:deploy

Click here to find out more about Magento modes.

If you refresh your Magento store, you should be able to see your JS file being included.

Add Custom JS in Magento 2

If you need to add an external JavaScript library, for example a JavaScript file from Google, you can add a src_type attribute to the <script> tag within the layout file.

<?xml version="1.0" ?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <script src="" src_type="url" />

Note: This article is based on Magento Community/Open Source version 2.1.