Sunday, 4 March 2018

How To add JS file in frontend for all pages in magento 2

How To add JS file in frontend for all pages in magento 2
requirejs-config.js under :- /app/design/frontend/your_vendor/your_theme/

To load a custom main.js file on all pages (in the RequireJS-way) this is a good way:
1) Create main.js
Create main.js within the theme folder
<theme_dir>/web/js/main.js
with this content:-------------

define([
  "jquery"
],
function($) {
  "use strict";

  // Here your custom code...
  console.log('Hola');

});

2) Declare main.js with a requirejs-config.js file
Create a requirejs-config.js file within the theme folder:

<theme_dir>/requirejs-config.js

with this content:

var config = {

  // When load 'requirejs' always load the following files also
  deps: [
    "js/main"
  ]

};


--------------------------------------------
app/code/your_vendor/your_theme/Magento_Theme/layout/default_head_blocks.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <!-- 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 -->
        <css src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" src_type="url" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
        <link src="http://fonts.googleapis.com/css?family=Montserrat" src_type="url" />
    </head>
</page>

2 comments: