Posted 30 days ago. Visible to the public.

Unpoly: Loading large libraries on-demand

When your JavaScript bundle is so massive that you cannot load it all up front, I would recommend to load large libraries from the compilers that need it.

Compilers are also a good place to track whether the library has been loaded before. Note that including same <script> tag more than once will cause the browser to fetch and execute the script more than once. This can lead to memory leaks or cause duplicate event handlers being registered.

In our work we mostly load all JavaScript up front, since our bundles are small enough. We recently had a case where we had a very large geo map library that we only wanted to load when it is used. The code we used for that looked something like this:

var hugeLibraryLoaded; up.compiler('.map', function($map) { hugeLibraryLoaded = hugeLibraryLoaded || $.getScript('/huge-lib.js') hugeLibraryLoaded.then(function() { HugeLibrary.init($map) }) })

Note how the library will only get loaded once even after compiling multiple <div class="map"> elements.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Henning Koch
Last edit:
30 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev