Originally posted in Medium

During the initial days of development on Force.com platform, only a minimal use of JavaScript was advisable when working with Visualforce pages. However, JavaScript as a language has come a long way and modern day applications require rich and responsive UI. Hence applications are approached as a single page application.

Difference between a normal Visualforce lifecycle versus a SPA application lifecycle.

From the above diagram one can easily infer that in SPA applications, the first-time load serves the HTML and any client side interaction after the initial load uses AJAX to load data as a JSON.

With SPA architecture, the client and the service are independent. You could replace the entire backend that runs the service. As long as you don’t change the API, you won’t break the client. The reverse is also true — you can replace the entire client app without changing the service layer. For example, you might write a native mobile client that consumes the service.

To write SPA applications, Visualforce can be used just as a container and one could write the whole application using Apex (JavaScript Remoting) + Javascript (Vanilla Script or Jquery or Angular or React or any other framework) +CSS.

If you have never coded in JavaScript but always coded in strongly typed languages like Java, C# or Apex, there is definitely a learning curve to get used to a functional language like JavaScript. Here are some of the concepts of JavaScript that really took time to wrap my head around, and might be difficult for someone who has only done Visualforce and Apex programming and is new to JavaScript. Note that these tips are applicable to ES5 only.

Tips for working with JavaScript

1. Syntax For Immediately Invoked Function Expressions

(function () {     
   // logic here 
})();

The above is a syntax for IIFE in JavaScript. It is worth noting you can pass and return a function in JavaScript.

2. JavaScript Closures

JavaScript variables can belong to the local or global scope.

Private variables can be made possible with closures.

A quick syntax reference is as below. This is also known as module design pattern in ES5.

(function() {      
    // declare private variables and/or functions      
  return {       
    // declare public variables and/or functions     
  }  
})();

Example code:

var add = (function () {
    var counter = 0;
    return function () {
       return counter += 1;
    }
})();
add();
add();
add();
// the counter is now 3

3. Callbacks

A callback is a function to be executed after another function is executed. It’s hard to understand just by reading the definition, so here’s an example:

If you want to call function do_b after function do_a the code looks something like

function do_a(){
 console.log( 'do_a: this comes out first');
}
function do_b(){
 console.log( 'do_b: this comes out later' );
}
do_a();
do_b();

However, JavaScript is an event driven language. If do_a takes longer than do_b, the result of do_b comes out first than do_a

So how do we make sure do_b comes out after do_a in that situation? This is where callbacks come in handy.

function do_a(callback){
  setTimeout( function(){
   // simulate a time consuming function
   console.log( 'do_a: this takes longer than do_b' );
   // if callback exist execute it
   callback && callback();
  }, 3000 );
}
function do_b(){
   console.log( 'do_b: now we can make sure do_b comes out after do_a' );
}
do_a(function(){
  do_b();
});

Note that you can easily get into a problem known as callback hell and ES6 Promises can solve this issue. We will not discuss Promise as a part of this blog.

Tips when working with JavaScript inside Visualforce

1. Keep all JavaScript Inside Static Resource

<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>

2. Establish a development workflow for your application

For JavaScript heavy apps, it’s a good idea to establish a workflow for your development using a module bundler like webpack or a task or a build runner like gulp. We will not be digging into details here. If you are building apps using React and Redux there is already a blog post from one of the evangelists on how to set your development workflow.

3. JavaScript Remoting for Server Side calls

If you are using JavaScript, it’s advisable to use JavaScript Remoting or JavaScript Remote Objects for your apps. Here is a simple example:

Visualforce Page

<apex:page controller="TestController" showHeader="false" sidebar="false" standardStylesheets="false" cache="false" expires="0" docType="html-5.0" applyHtmlTag="false">
<html lang="en">
    <head>
     <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <title>Javascript Tips</title>
    <script>
            window.configSettings = {
                user:{
                    id : '{!$User.Id}',
                    firstName : '{!$User.FirstName}',
                    lastName : '{!$User.LastName}',
                    uiThemeDisplayed : '{!$User.uiThemeDisplayed}', 
                },
remoteActions: {
                    helloWorld : '{!$RemoteAction.TestController.helloWorld}',
                }
            }
    </script>
     <apex:includeScript value="{!URLFOR($Resource.MyJavascriptFile)}"/>
    </head>
    <body>
      <div> ....</div>
    </body>
</html>
</apex:page>

Apex Controller class

public with sharing class TestController {  
 @ReadOnly    
 @RemoteAction    
  public static String helloWorld() { 
     return 'hello word' ;  
  } 
}}

Static Resource JavaScript(MyJavascriptFile.Js)

(function (window) {     
   Visualforce.remoting.Manager.invokeAction(
     window.configSettings.helloWorld,
     function(result, event) {
       if (event.status) {
        console.log(result);
       } else {
          //handleReturnError(event);
       }
     },      
        {buffer: true, escape: true}
    );
})(window);

Summary

JavaScript is continuously evolving and so are frameworks. At this point, there is no “one approach” to building web applications. You can use Visualforce as the container and choose any framework to build applications on the platform. However, as it continues to mature, Lightning Components Framework is the future. This primarily uses JavaScript so knowing the above concepts and diving deeper into the vast world of JS becomes even more important.


Does your dev team need help?

We’ve launched 250+ products on the AppExchange and our technical experts know the in’s and out’s of Lightning. We can help get answers fast. Let’s talk!