Skip to content

Instantly share code, notes, and snippets.

@Leland
Created March 9, 2021 21:12
Show Gist options
  • Save Leland/c9775e8b2e9541f7d4e5be0f7944a86d to your computer and use it in GitHub Desktop.
Save Leland/c9775e8b2e9541f7d4e5be0f7944a86d to your computer and use it in GitHub Desktop.
My notes from a Require.js tutorial in Magento 2

Require.js

How the Require.js system works

  • It is a system that allows Javascript on the frontend to be load async

    • The amount of JS that blocks render is fairly small
    • And the remaining JS that's needed can be loaded at a low priority
  • It's also a way to manage dependencies on JS modules

    • Concating every single bit of JS into one big file resolves race conditions, but means that frontend users download a TON of JS.
    • Require.js gets around this by using a define(['dep']) approach, that allows dependencies to be wired in on load time.
    • It's also idempotent, so that if something is already loaded, it won't load twice.
  • It's a way to use Javascript in a modular fashion

Downsides

  • Sometimes the dependency tree is really long.
  • That means that the time to execute a specific module can be overly long if it has a series of dependencies.
  • AKA it takes too long.

How Magento uses it

  • deps

    • A way to load specific JS modules on certain pages (or all) in a config
  • mixins

    • Which let you modify behavior of existing JS objects/functions/whatever
  • shims

    • Which let you load in non-Require.js syntax in a normal way
  • map

    • Which lets you override existing modules in favor of whatever file you want!
  • text/x-magento-init, as well as data-mage-init and a whole host of other fun HTML approaches.

How you can use it

  • Git approach

How we’ve customized it at this company

  • Webpack
  • Gulp
  • Flattened dependency trees
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment