The problem

Sometimes it can be a little frustrating when developing Lightning Components because you want to follow the DRY principle (Don’t Repeat Yourself) because the framework does not yet offer a suitable way of accessing a shared library of code. There is a solution available in the open source version, but it’s not yet available on the platform.

A solution

All Lightning Components can load static resources and to conserve loading, they will only load a static resource once even if they are referenced by multiple components. We can create a static resource and create our shared library of code from there!

First, let’s create our static resource and call it “SharedLib”:

(function(w){
   w.shared = {
      doSomething: function(){
         alert('hello world');
      }
   }
})(window);

Next is to create our Lightning Component:

<aura:component>

   <ltng:require scripts="/resource/SharedLib" afterScriptsLoaded="{!c.handleLoaded}" />

   <button onclick="{!c.handleLoaded}">Click!</button>

</aura:component>

This is the code for the controller for our component:

({
   handleLoaded: function(component, event, helper) {
      window.shared.doSomething();
   }
})

So what’s going on?

As soon as the Lightning Component is rendered it will request to load in our SharedLib static resource. This is the line which is responsible for doing this:

<ltng:require scripts="/resource/SharedLib" afterScriptsLoaded="{!c.handleLoaded}" />

This then calls the handleLoaded function within our controller and then calls our code loaded within our static resource as such:

window.shared.doSomething();

What about the LockerService

This has been tested with the LockerService activated and it works pretty well!

To conclude

OK, we’ve been told multiple times never to assign variables directly to the window object in JavaScript to ensure maximum encapsulation, so if you are going to use this approach try and use a namespace to avoid conflicting with other JavaScript which may be loaded on the page.

Let me know what your thoughts are on using this approach!