如何在 JavaScript API 中使用 jQuery?

4
我希望开发一个JavaScript网络服务,网站只需加入一行代码即可使用,类似于Google Analytics的用法。我想在我的JavaScript代码中使用jQuery,但我不希望它与主机网页上可能已经存在的任何JS库冲突。
基本上,在我的主JavaScript文件中,最终用户将包含在他们的网页中,我想要做的事情是:
document.write('<script type="text/javascript" ' +
           'src="http://mydomain.com/js/jquery-1.4.2.min.js"></script>');

我想在我的代码库中使用jQuery,想知道这是否是在JavaScript API中使用jQuery的正确方法,或者是否需要考虑更多因素。如果有任何人能提供示例或文章,我将不胜感激。

3个回答


1

0
前一段时间我制作了一个书签生成器无耻的广告,它启用了jQuery。
你可以查看正在执行的代码,特别是这一块:
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);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接