Use static resource in Visualforce

Salesforce being Platform as a Service (PAAS) provides us with a facility to upload, manage and use the content that is static (not changing) for your organization, and it can be stored under “Static Resources“. It can be a Javascript file, CSS file, an image or even a zip file containing all the files required in one zip file. It is also helpful in cases where we need to use external third party files like Bootstrap inside Salesforce. In the post, we’ll see how to use the static resource in Visualforce – Salesforce.

There are different ways to use the static resources in our visualforce page.

Let say there is a single file like an image file or CSS file and you want to refer it on the visualforce page then you do that directly using “$Resource.resourceName
to refer to the static resource where ‘$Resource‘ is a global variable to use any static resource within the visualforce page.

We can use this image in our code using expression {$Resource.quoteImage}. 
Below are some other examples as well:

Visualforce Page:

<apex:page >

    <!-- An image can be referenced like this -->
<img src="{!$Resource.quoteImage}"/>
 
<!-- Similarly any CSS file can be referenced like below -->
 <apex:stylesheet value="{!$Resource.sampleStaticCss}"/>
    
</apex:page>

Also, there is another situation where you want to refer multiple files in a static resource just like a resource bundle for a website which contains the HTML file, Javascript file, CSS file in a single folder so you can create a zip folder and upload that folder in the static resource. Now you can access the files which are inside the Static resource and use it accordingly in Visualforce Pages or Lighting Components.

To reference a particular file at a given location we can use
“URLFOR(nameOfStaticResource, RelativePathOfFile)” function where we need to provide the path of the file in the context of the zip, along with the name of the static resource while referencing in Visualforce page code.
The code snippet shows how to use and refer them on Visualforce Page

Visualforce Page:

<apex:page >
    
    <!-- Static Resources for CSS -->
    <apex:styleSheet value="{!URLFOR($Resource.XStaticResourceBootstarp	, 'bootstrap-4.5.0-dist/css/bootstrap.css')}"/>
    <apex:styleSheet value="{!URLFOR($Resource.XStaticResourceBootstarp	, 'bootstrap/css/bootstrap.min.css')}"/>
    
    <span class="border border-primary">Sample-1</span>
    <span class="border border-danger">Sample-2</span>
</apex:page>

Output: