I have experience with Magento 1, and there adding a custom javascript file was very straightforward and logical.
But when it comes to Magento 2, I can't figure out how to add a new js file, where I would put little code snippets that affect different places around the page.
For example, I want to modify 'last viewed items' block on the home page, and use jQuery there and then maybe another script that changes some CSS dynamically somewhere (for example).
I find it very comfortable to do it in one single file like I used to do in Magento 1. Also, Magento official docs didn't help me since it didn't provide information clear enough.. I guess it has something to do with requireJS but is there another way? If not then can someone explain it a little clearer than Magento official docs did?
PS. Tried adding my custom.js file to head block trough XML, but then I didn't get access to jQuery.
Thanks!
2 Answers 2
jQuery is already pre-packaged with Magento2, there is no need to implement it on your own, however, you have to utilize it.
To add JS to your theme you have several possibilities.
By utilizing default_head_blocks.xml in app/design/frontend/Vendor/Theme/Magento_Theme/layout/:
Example Content:
<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>
If you inject JS this way, dont forget to wrap your JS into the requirejs-conform way:
require(['jquery'], function($){ /* Code... */ })
Or: by utilizing requirejs-config.js in your themes root folder.
Simply add Deps to it, example:
var config = {
deps: [
"js/main",
],
map: {
'*': {
'owlcarousel': 'js/owl.carousel.min',
'sticky' : 'js/jquery.sticky',
'tether' : 'js/tether.min',
'bootstrap': 'js/bootstrap.min'
}
},
"shim": {
"owlcarousel": ["jquery"],
"tether": ["jquery"],
"bootstrap": ["jquery"]
}
};
In aboves example I register main.js by calling it in the Deps. The path is without the .js extention, requirejs is handeling this on its own.
Your main.js should be located at web/js/ in your theme.
The content of main.js should be like this:
define([
"jquery",
"whatever lib you wanna use..."
],
function($) {
"use strict";
$(document).ready(function($){
console.log("DID IT! jQuery log complete.");
});
return;
});
-
I have tried the first option, but then when I tried to use jQuery on sample.js(in your case), it didnt work. It gave error which said something like "$ (or jQuery) is not defined". Will try the second option soon. But for now I copied theme.js from Magento Blank theme to my own theme, and by surprise it worked like that. I can even use jQuery that way. (My theme inherits from Magento Blank)raouaoul– raouaoul2017年01月24日 09:24:09 +00:00Commented Jan 24, 2017 at 9:24
-
1if jQuery is not defined you need to wrap your code in
require(['jquery'], function($){ /* your code... */ });- hope it helps.Max– Max2017年01月24日 09:56:35 +00:00Commented Jan 24, 2017 at 9:56 -
I've updated the answer again for better understanding! Glad that I could helped you.Max– Max2017年01月24日 10:22:32 +00:00Commented Jan 24, 2017 at 10:22
-
@Max I tried your method ( magento.stackexchange.com/questions/206124/…) i posted a question , can you please check.inrsaurabh– inrsaurabh2017年12月17日 13:34:13 +00:00Commented Dec 17, 2017 at 13:34
-
You need to add the
sample1.jsinside therequirejs-config.jsmap object otherwise you get errors. Also after clear all your cache!php bin/magento cache:cleanphp bin/magento cache:flushphp bin/magento setup:upgradephp bin/magento setup:di:compileNick Howarth– Nick Howarth2022年08月26日 13:06:36 +00:00Commented Aug 26, 2022 at 13:06
Please put JS in web/js folder in app/design/frontend/vendorname/themename and call into Magneto_Theme/layout/default_head_blocks.xml file..
<script src="jquery.js" />
<script src="js/modernizr.js" />
and Create one requirejs-config.js in the Magento_Theme.
var config = {
map: {
'*': {
modernizer : 'Magento_Theme/js/modernizr.js'}
}
};
Then remove pub/static folder expect .htaccess file and remove cache and run it..
-
is it usefulr for u?Moin Malek– Moin Malek2017年01月25日 05:59:33 +00:00Commented Jan 25, 2017 at 5:59
-
i think we should remove js from the end of the filegh darvishani– gh darvishani2020年01月06日 18:02:43 +00:00Commented Jan 6, 2020 at 18:02
-
@MoinMalek Any help thanks magento.stackexchange.com/q/321141/57334zus– zus2020年08月30日 06:09:52 +00:00Commented Aug 30, 2020 at 6:09
Explore related questions
See similar questions with these tags.
requireordefinein JS, since require-js handles things differently.