Inefficient JavaScript loading
Why is this an issue?
Loading JavaScript files from external content delivery networks (CDNs) or inline sources instead of Salesforce static resources introduces both performance and security risks.
Performance concerns:
External CDN requests add network latency and depend on third-party availability.
Scripts loaded from external sources cannot benefit from Salesforce's caching mechanisms.
Multiple external requests increase page load time.
Security concerns:
External scripts can be modified by attackers (supply chain attacks).
CDN compromises could inject malicious code into your application.
Content Security Policy (CSP) violations may occur in Lightning Experience.
Salesforce recommends loading all third-party JavaScript through static resources, which are served from Salesforce's secure infrastructure.
Examples
Visualforce
Example of incorrect code:
<apex:page>
<script src="https://cdn.example.com/library.js"></script>
</apex:page>
Example of correct code:
<apex:page>
<apex:includeScript value="{!$Resource.MyLibrary}"/>
</apex:page>
Aura components
Example of incorrect code:
<aura:component>
<ltng:require scripts="https://cdn.example.com/library.js"/>
</aura:component>
Example of correct code:
<aura:component>
<ltng:require scripts="{!$Resource.MyLibrary}"/>
</aura:component>
Lightning Web Components
Example of incorrect code:
import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
connectedCallback() {
const script = document.createElement('script');
script.src = 'https://cdn.example.com/library.js';
document.head.appendChild(script);
}
}
Example of correct code:
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import myLibrary from '@salesforce/resourceUrl/MyLibrary';
export default class MyComponent extends LightningElement {
renderedCallback() {
loadScript(this, myLibrary)
.then(() => { /* library loaded */ })
.catch(error => { console.error(error); });
}
}
How can I fix violations?
Download the library: Obtain the JavaScript file from its official source.
Create a static resource: Upload the file as a static resource in Salesforce Setup.
Update your code: Replace the external URL with a reference to the static resource using the appropriate method for your framework.
When should I disable this rule?
You may dismiss specific violations when:
The script is from a Salesforce-approved external source that is explicitly allowed.
You are loading analytics or tracking scripts that must come from external sources for accurate data collection.
Resources
