Adding JavaScript and jQuery to Visualforce pages

Visualforce is pretty tolerant of how custom JavaScript is added, but this post suggests a couple of patterns to use (where possible):

  • External JavaScript file references or local JavaScript is best placed at the end of the page rather than the beginning which looks a bit strange at first sight. The benefit is that the page content can then be rendered by the browser before the browser becomes blocked loading the external JavaScript file and then executing that file and the local Javascript. So a potential page load delay is avoided, with the JavaScript work being completed in the user’s “thinking time” as they first see the page content.
  • It is easy to unintentionally add references to Javascript’s global scope and so potentially interfere with other references in that scope. In JavaScript scope is delineated by functions (not by blocks – curly brackets have no impact on scope) so var declarations should always be used and should always be used within a function.

So when not using external libraries put this executed (via the ()) anonymous JavaScript function (to create a new scope) at the end of the page:

<apex:page ...>
    <apex:sectionHeader .../>
    <apex:pageBlock ...>
        ...
    </apex:pageBlock>

<script>
(function() {
    // All the custom JavaScript goes in here
    // Always use var
    var i = ...;
    ...
})();
</script>
</apex:page>

and when using jQuery put both the include and the executed anonymous JavaScript function at the end of the page:

<apex:page ...>
    <apex:sectionHeader .../>
    <apex:pageBlock ...>
        ...
    </apex:pageBlock>

<apex:includeScript value="{!URLFOR($Resource.jQueryZip, 'jquery.js')}"/>
<script>
(function($) {
    // All the custom JavaScript goes in here
    // Always use var
    var i = ...;
    // Use $ in here for jQuery
    var j = $('table.notes');
    ...
})(jQuery.noConflict());
</script>
</apex:page>

This allows $ to be used as the reference to jQuery within the function, while ensuring that whatever the symbol $ was set to before jQuery was included is restored via the noConflict call.

Advertisements