angelokh
angelokh

Reputation: 9428

Build a custom jQuery without $ dollar sign

I have a javascript lib that might run on different kinds of websites, such as wordpress or magento. The js lib dynamically loads jQuery and call noConflict to assign to another variable namespace in onereadystatechange() of script element. However, if the site also loads Prototype js before my js lib, a conflict between Prototype and jQuery can happen.

Before onereadystatechange callback is called, page might be parsed and a Prototype function might be called. If that Prototype function uses any '$', it causes that function to fail because that dollar sign '$' is still jQuery, not Prototype (before jQuery.noConflict() is called).

Can I build a custom jQuery not to use '$' at all, so there will be no need to load Prototype again for above reason?

EDIT 1:

Here is the process my js library (mylib.js) will be used on a website and how the jQuery might have conflict with Prototype from that website.

onepage.html from others' website

<head>
  <script src="prototype.js" type="text/javascript"></script>
  <script src="mylib.js" type="text/javascript"></script>
</head>

mylib.js

1. If jQuery is not defined, create a script element with jQuery src and insert to header.
2. In the script element, attach event onreadystatechange.
  element.attachEvent('onreadystatechange', function () {
  if (elem.readyState == 'loaded' || elem.readyState == 'complete') {
      callback();
    }
  });
3. in callback(), I called noConflict().
   var callback = function() {
     return function() {
        if (window['jQuery'] && hasJQueryReqVersion()) {
           window.myJQ = jQuery.noConflict(true);
        }
     }
   }();

Problem is before callback() is called, Prototype might be called and it would accidentally use '$' which has been overridden by jQuery.

Upvotes: 4

Views: 1776

Answers (2)

ajtrichards
ajtrichards

Reputation: 30565

Load jQuery first and call $.noConflict() immediately.

You can also set jQuery to totally avoid the $ using something like

var JQry = jQuery.noConflict();

Upvotes: 2

Babak Naffas
Babak Naffas

Reputation: 12561

You have control over the order in which the libraries are loaded. Load the jQuery library first (by having that script node in your <head> and immediately make the call to $.noConflict() before allowing the other scripts to load.

Upvotes: 3

Related Questions