How to Create and Reference Static Resources in Salesforce?

How to Create and Reference Static Resources in Salesforce?

Static Resources :

Static resources allow you to store content like archives (.jar and .zip file), images, JavaScript, cascading style sheets (CSS) and other files. All those files which are stored as a static resource can be later referenced in a Visualforce page and Lightning Component.The maximum limit for a single static resource is 5 MB, and a salesforce org can have maximum 250 MB of static resources in total.

Advertisement

Steps to create a static resource :

  1. Go to setup and enter static resources in the quick find box and select static resources.
    static1
  2. Click new and a form will open.
    static2
  3. Fill all the required details on the form.
    static3
  4. Click save.

Referencing a Static Resource :

There are  two ways of referencing a static resource in a Visualforce page :

      1.  A stand-alone file can be referenced using $Resource.<resource_name> as a merge field, where <resource_name> is the name you specified when you uploaded the resource. For example :
        <apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
        <apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
      2. A file in an archive can be referenced using URLFor Function. URLFOR Function requires two parameters, the first parameter is the name of static resource which store an archive file and the second parameter is the path of the required file within the archive.For example:
    <apex:image url="{!URLFOR($Resource.TestZip,'images/Bluehills.jpg')}" width="50" height="50"/>
    <apex:includeScript value="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>

Referencing a static resource in the lightning component:

Lightning component must include ltng:require tag to use static resource. ltng:require enables you to load external CSS and JavaScript libraries after you upload them as static resources. For example :

<ltng:require styles="/resource/datatable/DataTables-1.10.16/media/css/jquery.Datatable.min.css" scripts='/resource/jquery,/resource/Datatable/DataTables-1.10.16/media/js/jquery.dataTables.min.js' afterScriptsLoaded="{!c.scriptsLoaded}"/>

Popular Salesforce Blogs