4

I am looking to develop a javascript web service that a website could include in one line of code similar to how google analytics is used. I would like to use jQuery in my javascript code, but I don't want it to conflict with any js libraries that may already be present on the hosting webpage.

Basically, inside the my main javascript file that an end user would include in their webpage, I would want to do something like:

document.write('<script type="text/javascript" ' +
           'src="http://mydomain.com/js/jquery-1.4.2.min.js"></script>');

...to make jquery available within my code library. I'm wondering if this is the proper way to go about using jquery in a javascript api, or if there are more considerations to be made. I'd appreciate any examples or articles anyone can suggest.

3 Answers 3

1

See: How to build a web widget (using jQuery) tutorial by Alex Marandon. It explains many approaches to exactly what you are trying to do.

Sign up to request clarification or add additional context in comments.

Comments

1

Use jQuery.noConflict()

Comments

0

A while back I made a bookmarklet generator shameless plug that's jQuery enabled.

You can check out the code that's being executed, specifically this chunk:

if (!window.zbooks)
  {
    //if zbooks hasn't been set, initialize it

    //s used for the Script element
    var s = document.createElement('script');
    //r used for the Ready state
    var r = false;
    //set the script to the latest version of jQuery
    s.setAttribute('src', 'http://code.jquery.com/jquery-latest.min.js');
    //set the load/readystate events
    s.onload = s.onreadystatechange = function()
    {
/**
 * LOAD/READYSTATE LOGIC
 * execute if the script hasn't been ready yet and:
 * - the ready state isn't set
 * - the ready state is complete
 *   - note: readyState == 'loaded' executes before the script gets called so
 *     we skip this event because it wouldn't have loaded the init event yet.
 */
      if ( !r && (!this.readyState || this.readyState == 'complete' ) )
      {
        //set the ready flag to true to keep the event from initializing again
        r = true;
        //prevent jQuery conflicts by placing jQuery in the zbooks object
        window.zbooks = {'jQuery':jQuery.noConflict()};
        //make a new zbook
        window.zbooks[n] = new zbooks(c);
      }
    };
    //append the jQuery script to the body
    b.appendChild(s);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.