-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Description
While working on my "modern web development guide", which mentions Vue.js a good amount, I wanted to explain the various ways that third-party javascript libraries can be used by designers.
Designers are often used to having a vendor
folder to plop in libraries like jQuery, which are then included using the traditional way (via a <script>
tag in the HTML).
I'm writing an FAQ on lazy-loading and wanted to explore this route to see if it would work over the less intuitive lazy-loading that webpack/browserify do via require
. The question I'm trying to answer is just what are all the primary techniques to reduce the size of the app.js
bundle.
During my experiments, I found out a few things:
1. Including <script>
tags in the HTML that gets swapped in by vue-router does nothing
This applies to both .vue
and .ejs
files. Adding this doesn't load jQuery when the view is swapped in:
<script src="/vendor/jquery.js" async></script>
I'm curious, why does that not work? I think this traditional (expected) way of doing things would be a welcome convenience for designers.
2. It's possible to lazy-load 3rd party libraries using <script>
and vue-router
You just have to do it in a round-about way within a .vue
file using the component's ready
method. Example:
<script>
export default {
ready() {
if ( ! window.jQuery ) {
var s = document.createElement("script")
s.type = "text/javascript"
s.src = "/simple/vendor/jquery.js"
s.async = true
this.$el.appendChild(s)
}
},
methods: {
submit: function () {
var $ = window.jQuery
// do something with $...
}
},
That actually works. 😄
Could the Lazy-loading documentation cover this technique (maybe also pros/cons)?
3. Libraries don't get unloaded when the view is swapped out
Another observation that I noticed is that once a third-party library gets loaded in a single-page app, it never gets unloaded. So if an app has a bunch of libraries, and the user visits "all the pages", then they'll be using up a good amount of memory since none of the global JS that gets attached to window
ever gets unloaded. I was also wondering what "the right" way to do this is (and maybe the docs could also cover it?).
Curious to hear your thoughts!