Sunday, March 15, 2015

jQuery in custom namespace

A re-usable javascript component that depends on jQuery may need to repackage jQuery in a custom namespace to avoid overriding other versions of jQuery loaded onto a third party host page. Fortunately the jQuery project makes it easy to move the core API to a namespace. Just download the uncompressed developer version of jQuery, and replace the following block of code at the top of the file:

    if ( typeof module === "object" && typeof module.exports === "object" ) {
  // For CommonJS and CommonJS-like environments where a proper `window`
  // is present, execute the factory and get jQuery.
  // For environments that do not have a `window` with a `document`
  // (such as Node.js), expose a factory as module.exports.
  // This accentuates the need for the creation of a real `window`.
  // e.g. var jQuery = require("jquery")(window);
  // See ticket #14549 for more info.
  module.exports = global.document ?
   factory( global, true ) :
   function( w ) {
    if ( !w.document ) {
     throw new Error( "jQuery requires a window with a document" );
    return factory( w );
 } else {
  factory( global );
with something like this:

        global.myNameSpace = global.myNameSpace || (global.myNameSpace = {});
        global.myNameSpace.jQuery = factory( global, true );