I've read 3 pages of Google Results on how to load a JS file for all pages and still am not able to do it.
I've got a few doubts, hope somebody can clear them out.
-
Do I need to create a module inside
app/code
with therequirejs-config.js
? Or I can put arequirejs-config.js
inside my theme instead? -
What should I put inside
requirejs-config.js
? -
What should the code look like inside my
.js
file? I saw that you can't use jQuery'sdocument.ready
and you must have adefine([
-
What should I put inside
define([
? -
If I've got third party jQuery modules, do I have to edit them to make them work?
-
Do I need to put xml somewhere to tell magento that my.js file exists?
-
If I create a module inside
app/code
with all the js code there, would it include all the stuff in all pages? How can I achieve that?
Best Answer
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:
In short: we declare dependencies at the start, e.g.
"jquery"
. We define as function's parameter the variable name for using the dependency within the function, e.g."jquery" --> $
. We put all our custom code withinfunction($) { ... }
.2) Declare
main.js
with arequirejs-config.js
fileCreate a
requirejs-config.js
file within the theme folder:<theme_dir>/requirejs-config.js
with this content:
"js/main"
is the path to our custommain.js
. The ".js" extension is not required.Our
requirejs-config.js
will be merged with otherrequirejs-config.js
defined in Magento.RequireJS will load our
main.js
file, on each page, resolving dependencies and loading files in an async way.Optional: Including third-party library
This is the way to include third-party libraries.
1) Add the library in
web/js
:<theme_dir>/web/js/vendor/jquery/slick.min.js
2) Open
requirejs-config.js
and add this content:It looks more complicated than what it actually is.
3) Add the dependency within
main.js
: