Always use $Resource while loading scripts and styles

Recently, I was building lightning component to show charts. For that, I wanted to use Charts.js library into my component. Along with that, I had another script “execute.js” which I want to load. So in total 2 scripts I wanted to load at the start of page. After loading the scripts, I want to call method “initialiseSetup” from lightning controller.

I created zip file, added these two scripts and uploaded them in static resource with name “chart_scripts“. I used following syntax to achieve that. Pretty straightforward right?

<aura:component >
    <ltng:require scripts="/resource/chart_scripts/Chart.min.js, /resource/chart_scripts/execute.js" afterScriptsLoaded="{!c.initialiseSetup}">
    </ltng:require>
</aura:component>

Suddenly I saw there is some mistake in my execute.js, I did some modifications into the file, override existing file with newly modified file into zip and uploaded in same static resource. It supposed to work right? but wait. It didn’t. I tried to check if there is any logical errors in script, but no.

Then I checked if the updated script is getting referred or not through network tab of Chrome browser. Surprisingly it was referring to old JavaScript file which I uploaded initially. Salesforce basically cached that file.

Upon researching I found the Salesforce official article regarding this behavior, as per the article:

It is highly advised to use URLFOR($Resource.ResourceName) instead of referencing /resource/ResourceName directly. Using URLFOR with the resource will put the current version number in the URL path, and that allows updates to the resource to get used instantly by the pages while maximizing the cacheability of each version.

And there I go, I did the same thing. Earlier, I provided relative URL paths for static resource instead of using global $Resource variable. I then changed the code as follows:

<aura:component >
    <ltng:require scripts="{!join(',', $Resource.chart_scripts+'/Chart.min.js',$Resource.chart_scripts+'/execute.js')}" 
                  afterScriptsLoaded="{!c.initialiseSetup}">
    </ltng:require>
</aura:component>

And voila! it worked. Its now referring to new file that you upload in static resource file rather than cached file.

So always make use of $Resource to refer static resource to avoid caching issues.