The purpose of this plug-in is to enable adding JavaScript on demand and remove 100 of script includes that we do on a page where massive client side scripting is involved. The plug-in code (bottom of this email) can be saved in a JS file and can be included in the head section of the page. Now come the interesting part –
Suppose you have JS files which are for various components of the page and a JS which is for a page. In a normal scenario we include the component JS files and page JS file in the main page itself using script tag, but when we use this plug-in we do something like this in the page JS file (where page JS file is a JS file created for a specific page)
jQuery.require(“component1.js”); jQuery.require(“component2.js”); jQuery.require(“component3.js”); jQuery.require(“some_jquery_plugin.js”); //rest of the code for the page JS file
Now you have to just include the page JS and it’s done. Also since the plug-in has been designed to accept array and allow chaining you can do something like this as well
jQuery.require([“component1.js”, ”component2.js”, “component3.js”]).require(“some_jquery_plugin.js”);
Further the benefit of this approach will be that suppose component1.js use a library to do some stuff and it is specific to component1 itself, in this scenario you will include that library inside component1.js itself.
jQuery.require(“library1.js”); //rest of the code
And this will ensure where ever you use component 1 it’s all required JS are included.
You can specify a default path for scripts by assign value to scriptPath as below
$.scriptPath = “\root\static\js”;
Also you can pass in following parameters when you call the require method
jQuery.require(“ie_lib.js”,{browserType:jQuery.browser.msie})
e.g. jQuery.require(“ui.js”,{callback:function(){initializeUI();}});
You can use all these parameters in one go like
jQuery.require(“xyz.js”,{ browserType:jQuery.browser.msie, callback:myCallback, cache:false }
I have tested the code on
`/ require is used for on demand loading of JavaScript require r1 // 2008.02.05 // jQuery 1.2.2 // basic usage (just like .accordion) $.require(“comp1.js”); *
(function($){ $.require = function(jsFiles, params) {
var params = params || {}; var bType = params.browserType===false?false:true;
if (!bType){ return $; }
var cBack = params.callBack || function(){}; var eCache = params.cache===false?false:true;
if (!$.require.loadedLib) $.require.loadedLib = {};
if ( !$.scriptPath ) { var path = $(‘script’).attr(‘src’); $.scriptPath = path.replace(/\w+.js$/, ‘’); } if (typeof jsFiles === “string”) { jsFiles = new Array(jsFiles); } for (var n=0; n< jsFiles.length; n++) { if (!$.require.loadedLib[jsFiles[n]]) { $.ajax({ type: “GET”, url: $j.scriptPath + jsFiles[n], success: cBack, dataType: “script”, cache: eCache, async: false }); $.require.loadedLib[jsFiles[n]] = true; } } //console.dir($.require.loadedLib);
return $; }; })(jQuery);`