嵌入其他站点的 JS - 如何使用 jQuery 而不搞乱其他 jQuery 安装?

发布于 2024-09-28 18:32:32 字数 384 浏览 0 评论 0原文

我正在开发一些将嵌入其他网站的 JavaScript(例如 Google Analytics 或 AdSense)。正在完成一些核心 JS——AJAX 请求、动画、JSON(P)。

我已经使用 jQuery 编写了原型,并且确实想继续使用它,但是如果嵌入到其他站点(如果他们也安装了 jQuery)(甚至可能是不同的版本),这可能会导致问题。

有没有好的办法解决这个问题?到目前为止,我得到的最好的解决方案是简单地将所有出现的 jQuery 替换为 kQuery,将 $ 替换为 $kQuery< /code>,所以不存在命名冲突。有什么建议吗?我怎样才能尽可能地与他们现有的 JavaScript 兼容?

I'm working on some JavaScript that will be embedded on other websites (think like Google Analytics or AdSense). There is some hardcore JS being done -- AJAX requests, animations, JSON(P).

I've written the prototype using jQuery, and really want to keep using it, but this might cause a problem when embedded on the other sites if they also have jQuery installed -- probably even a different version.

Is there a nice way around this? The best solution I've got so far is to simply replace all occurrences of jQuery with kQuery, and $ with $kQuery, so there is no naming conflict. Any suggestions? How can I be as compatible as possible with their existing JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔少女心 2024-10-05 18:32:32

jQuery 有一个 noConflict 模式;这就是你所需要的。 jQuery 在覆盖 window.jQuerywindow.$ 的原始值之前将它们保存为本地副本。

因此,解决方案是:

var kQuery = $kQuery = $.noConflict( true );

window.jQuerywindow.$ 替换为原始值,并返回对 jQuery 本身的引用


如果您不想更改您的代码,只需将其包装在:

(function( $ ){
   // Your code with $
})( $.noConflict( true ) );

There is a noConflict mode for jQuery; that's what you need. jQuery saves the original values of window.jQuery and window.$ as a local copy before it overwrites them.

So, a solution is:

var kQuery = $kQuery = $.noConflict( true );

Which replaces window.jQuery and window.$ with the original values and returns a reference to jQuery itself


And if you don't want to change your code at all, just wrap it in:

(function( $ ){
   // Your code with $
})( $.noConflict( true ) );
终难遇 2024-10-05 18:32:32
 this might cause a problem when embedded on the other sites if they also have jQuery installed -- probably even a different version

我认为这不是真的。我在至少 3 个不同版本的 jQuery 之间切换没有任何问题,它是 向后兼容

 this might cause a problem when embedded on the other sites if they also have jQuery installed -- probably even a different version

I don't think this is true. I've had no problems switching between at least 3 different versions of jQuery, it is backwards compatible

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文