REQUEST A DEMO

Dynamically Loading jQuery plugins

In previous iterations of Dovetail Agent, there have been jQuery plugins (i.e. spellCheck) that could potentially be used on any page in the web application, so each file containing the jQuery plugin code actually included on every page so the plugin would always be available for use.

 

This was accomplished with a server-side include file, and doing a Response.Write method for each included file:

 

Response.Write('');

This serves its purpose well, but the downside is that only a small percentage of the pages actually need the plugin. A slight change to the mechanics of including the files allows the plugin to be available only when required.

 

First, the Response.Write is removed from the server-side include file. Next, some new code gets added to the client-side page that handles usage of the plugin:

 

$(document).ready(function() {
    var $spellCheckAreas = $("textarea[id]:not(:disabled)");
    if($spellCheckAreas) {
      spellcheckLoader();
   }
}
 
function spellcheckLoader() {
   var spellcheckPlugin = document.createElement("script");
   spellcheckPlugin.src = strAppPath + "/code/jquery/jquery.spellcheck.js";
   spellcheckPlugin.type = "text/javascript";
 
   var header = document.getElementsByTagName("head")[0];
   header.appendChild(spellcheckPlugin);
}

 

This code gets executed by jQuery when the document for the page is ready. If there are textarea elements on the page, then the spellcheck plugin needs to be loaded into the document header. This is done by the spellcheckLoader function, which creates a javascript element for the correct source file, and appends it to the document header. The usage of the plugin happens right after the spellcheckLoader function is called, but I excluded it here for clarity.