Websites have morphed from design-driven “Digital Brochures” to developer-driven full-on customized applications, as discussed in the A Pretty Website Isn’t Enough article.
A Token Example
Okay, no problem, we add all of the <script> tags to the <head> and away we go! Ooops, but wait a minute. Putting <script> tags in the <head> is bad, because it’ll cause render blocking.
Sigh. So we move jQuery up into <head>, too, along with this script. Everything finally works, but Google PageSpeed Insights hates us, it’s frankly a mess, and is pretty fragile if we start introducing more complexity to the mix.
Calgon, take me away!
It’s all about Dependencies
That’s precisely what SystemJS can do for you.
What is this sorcery? I won’t get too deep into the nerdstuff here. We’re not going to use jspm (indeed, I’ve been reducing the package managers I use) or worry about any of SystemJS’s more esoteric features, but rather just focus on the practical application of SystemJS on a website. A good read is the ES2015: A SystemJS Odyssey article if you want more.
Let’s Get to the Code!
Okay, so if you’ve read this far, I assume you’re on board… or at least you’ve decided you might as well finish what you started. So let’s have a look at how this will all work.
First of all, we’ll allow you one external script tag on your web page, something that looks like this:
These config settings can go anywhere; all that’s required is that SystemJS is loaded already, so that the System object is available to allow us to set its config options.
Now let’s say we have a bit of code that depends on VueJS, we can just do this:
console.log("Vue and it's dependencies are now loaded!");
We’re telling SystemJS we want vue loaded, and it will go off and asynchronously load it and all of its dependencies, then execute the callback function when it’s all ready to go. So we can put any code that depends on Vue being loaded in there, and away we go!
We no longer have to worry about the order in which our <script> tags are listed. We just say what we need, and it gets loaded. Since SystemJS knows all about various module formats, we can do things like:
import $ from 'jquery';
import lazySizes from 'lazysizes';
import Vue from 'vue';
import VueResource from 'vue-resource';
// Do something
And then if we did:
console.log("main.js, jQuery, LazySizes, Vue, and Vue-Resource are all loaded!");
So get on board now…