main.jsसभी पृष्ठों पर एक फ़ाइल को लोड करने के लिए (आवश्यकताएँ में) यह एक अच्छा तरीका है:
1) बनाएं main.js
main.jsथीम फ़ोल्डर के भीतर बनाएँ
<theme_dir>/web/js/main.js
इस सामग्री के साथ:
define([
"jquery"
],
function($) {
"use strict";
// Here your custom code...
console.log('Hola');
});
संक्षेप में : हम शुरुआत में निर्भरता की घोषणा करते हैं, जैसे "jquery"। हम फ़ंक्शन के पैरामीटर को फ़ंक्शन के भीतर निर्भरता का उपयोग करने के लिए चर नाम के रूप में परिभाषित करते हैं, जैसे "jquery" --> $। हमने अपना सभी कस्टम कोड भीतर रखा है function($) { ... }।
2) main.jsएक requirejs-config.jsफाइल के साथ घोषणा
requirejs-config.jsविषय फ़ोल्डर के भीतर एक फ़ाइल बनाएँ :
<theme_dir>/requirejs-config.js
इस सामग्री के साथ:
var config = {
// When load 'requirejs' always load the following files also
deps: [
"js/main"
]
};
"js/main"हमारे रिवाज का रास्ता है main.js। ".Js" एक्सटेंशन की आवश्यकता नहीं है।
हमारे Magento में परिभाषित requirejs-config.jsअन्य के साथ विलय कर दिया जाएगा requirejs-config.js।
आवश्यकताएं हमारी main.jsफ़ाइल को प्रत्येक पृष्ठ पर, निर्भरता को हल करने और async तरीके से फ़ाइलों को लोड करने में लोड करेंगी ।
वैकल्पिक: तीसरे पक्ष के पुस्तकालय सहित
यह तीसरे पक्ष के पुस्तकालयों को शामिल करने का तरीका है।
1) पुस्तकालय में जोड़ें web/js:
<theme_dir>/web/js/vendor/jquery/slick.min.js
2)requirejs-config.js इस सामग्री को खोलें और जोड़ें:
var config = {
deps: [
"js/main"
],
// Paths defines associations from library name (used to include the library,
// for example when using "define") and the library file path.
paths: {
'slick': 'js/vendor/jquery/slick.min',
},
// Shim: when you're loading your dependencies, requirejs loads them all
// concurrently. You need to set up a shim to tell requirejs that the library
// (e.g. a jQuery plugin) depends on another already being loaded (e.g. depends
// on jQuery).
// Exports: if the library is not AMD aware, you need to tell requirejs what
// to look for so it knows the script has loaded correctly. You can do this with an
// "exports" entry in your shim. The value must be a variable defined within
// the library.
shim: {
'slick': {
deps: ['jquery'],
exports: 'jQuery.fn.slick',
}
}
};
यह वास्तव में यह क्या है की तुलना में अधिक जटिल लग रहा है।
3) के भीतर निर्भरता जोड़ें main.js:
define([
'jquery',
'slick'
],
function($) {
// ...
});