Home >How to Add/Remove JavaScript, CSS, Fonts in Magento 2

How to Add/Remove JavaScript, CSS, Fonts in Magento 2

Hi guys,

Welcome back to our Magento 2 tutorial!

Today we will discuss the methods to add statics resources to <head> and remove them in Magento 2. With simple but easy-to-understand examples, we hope that you can enjoy our guide and get more knowledge for your own.

Let’s get started now!

1. Include static resources in <head>

It is very common to customize pages using external libraries in Magento 2, but in case you want to use external libraries, you need to add JavaScript and CSS files.

JavaScript, CSS and other static files are added in the <head> section of the page configuration file. The default view of the page <head> is defined in vendor /magento/module-theme/view/frontend/layout/default_head_blocks.xml. 

If you want to add external files, you can extend this file into your custom theme.

Example: Create a file in the custom theme:


<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    <!-- Add local resources -->
    <css src="css/my-styles.css"/>
    <!-- The following two ways to add local JavaScript files are equal -->
    <script src="Magento_Catalog::js/sample1.js"/>
    <link src="js/sample.js"/>
    <!-- Add external resources -->
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" src_type="url" />
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
    <link rel="stylesheet" type="text/css" 
src_type="url" />

When adding external resources, the value src_type = “url” is required.

The path to assets is specified to one of the following locations:

  • <theme_dir>/web-
  • <theme_dir>/<Namespace>_<Module>/web-

Let’s take another instance for more details: 

If you want to add owl.carousel.css file into the website, follow this instruction as below: Add this line into the <head>:

<css src = "css / owl.carousel.css" />

2. Remove static resources

When you modify the page according to changes in the design, it is necessary to edit the page. However, if you do not want to use CSS, JavaScript, or font files, you can absolutely remove them. 

To delete these static resources, and the links are on the page <head>, you should change the following in the extend theme:


<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    <!-- Remove local resources -->
    <remove src="css/styles-m.css" />
    <remove src="my-js.js"/>
    <remove src="Magento_Catalog::js/compare.js" />
    <!-- Remove external resources -->
    <remove src="http://fonts.googleapis.com/css?family=Montserrat" />

For example: You desire to delete the calendar.css file because you don’t use this file. The calendar.css file is added from the file


You can use <remove src = “mage/calendar.css” /> to delete the file.


< Previous Post
Next Post >
+ posts