Magento 2 Js Frameworks

There is a running joke in the Magento 1.x community where we wished we had jQuery instead of Prototype as the main JavaScript framework. Magento went with Prototype as at the time Magento 1.x was first being built, Prototype was more mature than jQuery.

So with the Magento 2 overhaul we now have jQuery but it’s not the only Javascript library in Magento 2. But fear not as Magento uses it in tandem with other Libraries for good reasons.

RequireJs

So this is the main one and its single use is to allow for loading in Javascript dependencies asynchronously instead of requiring everything initially through the script tags. This can be used for custom modules to load in extra javascript models and to loading in other dependencies from the Magento install.

/*browser:true*/
/*global define*/
define(
    [
        'ko',
        'jquery',
	'underscore',
	'Magento_Checkout/js/model/shipping-service',
	'My_CustomModule/js/model/foo'
    ],
    function (ko, $, _, shippingService, foo) {
        'use strict';
    }
);

This also means that javascript libraries can be shared without the conflicting variable names, especially for jQuery.

Knockout

A lot of the data driven JavaScript in the cart and checkout is handled by KnockoutJS which observes view models and updates the DOM on the fly without requiring you to manipulate the DOM yourself through use of jQuery or Prototype. As mentioned this is used extensively on the single page checkout, but also for the cart mini display.

AngularJS

This looks to be be used for the web based installer. However, given it is available it may be possible to integrate it in to your theme with RequireJS. Please be aware that some search bots may have difficulty crawling sites using such themes.

jQuery

DOM manipulation which is not reliant on underlying data models, such as banners, now uses jQuery. This brings the ability to use some nice jQuery add-ons that are out there without the conflicting javascript variable names when combined with RequireJS. It also looks to provide the functionality for AJAX requests on the front end allowing you to use methods shown here.

Underscore

This provides some useful Javascript functions to manipulate Javascript arrays, functions, objects and collections. This library is not required for you to use but provides a great alternative to rolling your own functions for dealing with arrays.


Tags: magento2javascriptframeworksRequireJSKnockoutjQueryunderscore