Upload
meet-magento-italy
View
60
Download
2
Embed Size (px)
Citation preview
Javascript is a crazy language
TypeError: undefined is not a function
Magento 1
Sorting JS files is a big mess1
Dead scripts2
Wall of code3
RequireJS
NOOOOO! another JavaScript
Library
define(ID?, dependencies?, function)
AMD
Module Definition
define(['jquery', 'underscore'], function($, _) { // Do stuff});
RequireJS
Module Definition
<script data-main="scripts/main" src="scripts/require.js"></script>
// scripts/main.jsrequire(['foo', 'bar'], function(foo) { // Do stuff});
head.appendChild()
Wrapping upRequireJS
http://requirejs.org
Magento 2
Resource optimization
Resource optimization
Resource optimization
var config = { //Settings};
require-config.js
baseUrl
site / static / area / vendor / theme / locale
baseUrl
baseUrl + Vendor_Module/script + .js
Pathsvar config = { paths: { "module-name": "Vendor_Module/script" }};
Map map: { '*': { "menu": "Vendor_Module/js/menu" } }
define([ "jquery"], function ($) { 'use strict';
function awesomeMenu() { return "this is a private function"; } return function () { var message = awesomeMenu(); alert(message); }});
Shim
define([ “jquery”, “jquery-plugin” ], function($) { // do stuff });
shim: {
'jquery-plugin': {
deps: ['jquery']
}
}
Config config: { “module-name”: { key: “value” } }
define([“module”], function (module) { module.config().key});
Mixinsvar config = { 'config':{ 'mixins': { 'target/module': { 'Vendor_Module/script' : true } } }};
Do something between the checkout steps
config: { mixins: { 'Magento_Checkout/js/model/step-navigator': { 'js/checkoutCustomization': true } }}
define([ "jquery" ], function ($) { 'use strict';
return function (target) { target.next = function() { // do stuff }; return target };});
define(['jquery'], function ($) { return function (widget) {
$.widget('mage.SwatchRenderer', widget, {
updateBaseImage: function (images, context, isProductViewExist) { //do stuff }
}); return $.mage.SwatchRenderer; }});
Want more?
Plugins
define([ 'text!mage/gallery/gallery.html',], function (galleryTpl) { // Gallery});
text!
Plugins
define(['domReady!'], function (doc) { //This function is called //once the DOM is ready});
domReady!
Benefits1. Asynchronous module loading, deferred execution.
2. More clean and maintainable code.
3. Code & data sharing between different modules.
4. Global variables avoidance.
Write modular code!
“Using a modular script loader like RequireJS will improve the speed and quality of your code."
Questions?@Nuovecode github.com/nuovecode