[SalesForce] Load and execute Javascript on the fly (Stored in static resources some other place) with SFDC Buttons on layout

Use Case – There is Javascript execute button on Account page layout named 'Update Account' –

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")}

//JSsript code which updates account based on some logic 
...
..
//40 or 50 lines of Code

Problem with above button is it loads all this Javascript on every account pageview and kindof slows down each page view.
what if we have 2 or more buttons then again its more time to load. Is there any way we can store Javascript in static resources and then load it only when user clicks button and then execute it ?

Note: I already know that you can Create Apex Webservice method and then call it from JS but wanted to check if there is any alternate way to do this.

Best Answer

Each of your custom buttons could be written as so, letting 'RequireScript' determine whether your static resource script has already been loaded into the page (by another button).

If you can abstract the functions into a static resource file, the resource will only be loaded once and the button action can then call the function defined within the static resource.

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")}

{!REQUIRESCRIPT("/resource/YourStaticResourceJSFileName")}

//JSsript code which updates account based on some logic 
callYourFunctionDefinedInTheResource(arguments);

Here is a bit more info about the anti-caching number contained within the static resource URL path. Using static resources with Salesforce custom Javascript buttons

Related Topic