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.
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.
Use jQuery.noConflict()
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);
}
精彩评论