Magento 2: Add Local & External CSS and JS file

This article shows different ways to add CSS and JS files in Magento 2.

Add CSS & JS from Layout XML file

In this example, we are adding JS and CSS via layout file in your custom module.

app/code/YourCompany/YourModule/ view/frontend/layout/frontName_controllerName_actionName.xml


<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <!-- local CSS file -->
       <css src="YourCompany_YourModule::css/custom.css"/>

       <!-- local JS file -->
       <script src="YourCompany_YourModule::js/custom.js"/>
       <link src="YourCompany_YourModule::js/custom2.js"/>

        <!-- external JS file -->
        <script src="<host>/script.js" src_type="url" defer="defer" />

        <!-- external CSS file -->
        <css src="<host>/custom.css" src_type="url" />
        <link rel="stylesheet" type="text/css" src="<host>/custom2.css" src_type="url" />
    </head>
</page>

Add CSS & JS from phtml file

In this example, we are adding a custom phtml template file in the head section. In that phtml file, we can include the JS or CSS script.

app/code/YourCompany/YourModule/ view/frontend/layout/frontName_controllerName_actionName.xml


<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Template" 
                name="my_custom_js" 
                template="YourCompany_YourModule::custom_js.phtml"/>
        </referenceBlock>
    </body>
</page>

app/code/YourNamespace/YourModule/ view/frontend/templates/custom_js.phtml


<script id="myCustomJs" src="<host>/custom.js" defer></script>

Hope this helps. Thanks.