How to Add Custom CSS and JS in Magento 2

Magento 2 website allows the store owners/developers to customize the core features/design in order to improve the store functionality as well as the customer experience.
In this blog, we will learn how we can add custom JS/CSS files in Magento 2.

Magento 2 allow us to add custom JS/CSS files in Theme and in module/extension.

Method to add custom CSS and JS in custom Module:

Add your demo.css file at app/code/Mageclues/Demo/view/frontend/web/css/demo.css

body{
 background-color:green;
}

Add your demo.js file at app/code/Mageclues/Demo/view/frontend/web/js/demo.js

require([
    "jquery"
    ], function($){
    $(document).ready(function() {
        alert("Hello, Mageclues!");
    });
   });

Then, you need to add css and Js File to Your module layout File.
app/code/Mageclues/Demo/view/frontend/layout/demo_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd">
    <head>
          <css src="css/deom.css" />
          <script src="js/demo.js"/>
    </head> 
    <body>
	<referenceContainer name="content">
            <block class="Mageclues\Demo\Block\class" template="Mageclues_Demo::classfile.phtml"/>
        </referenceContainer>  
    </body> 
</page>

Then you need to run following command from CLI.

rm -rf var/cache/*
rm -rf var/page_cache/*
rm -rf pub/static/*
php bin/magento setup:static-content:deploy

Method to add custom CSS and JS in custom Theme:

Add your custom CSS file inside,

app/design/frontend/{Vendor}/{themename}/web/css/styles.css

Add your custom JS file inside,

app/design/frontend/{Vendor}/{themename}/web/js/scirpt.js

You need to call custom CSS/JS file from theme layout file default_head_blocks.xml at app/design/frontend/{Vendor}/{themename}/Magento_Theme/layout/default_head_blocks.xml

Put inside tag,

<css src="css/styles.css"/> 
<script src="js/scirpt.js"/>

Remove cache folder and refresh page.

It’s now working in all pages of website.

Thank You!

Related Posts

Leave a Reply

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