构建一个没有$ dollar符号的自定义jQuery [英] Build a custom jQuery without $ dollar sign

查看:75
本文介绍了构建一个没有$ dollar符号的自定义jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在不同类型的网站上运行的javascript库,例如wordpress或magento。 js lib动态加载jQuery并调用noConflict以分配给script元素的onereadystatechange()中的另一个变量名称空间。但是,如果该站点还在我的js lib之前加载Prototype js,则可能发生Prototype和jQuery之间的冲突。

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.

在调用onereadystatechange回调之前,可能会解析页面并且可能会调用原型函数。如果Prototype函数使用任何'$',它会导致该函数失败,因为美元符号'$'仍然是jQuery,而不是Prototype(在调用jQuery.noConflict()之前)。

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).

我可以构建一个自定义jQuery,根本不使用'$',因此上面的原因不需要再次加载Prototype吗?

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

编辑1:

以下是我的js库(mylib.js)将在网站上使用的过程以及jQuery如何与来自该网站的原型。

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来自其他人的网站

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);
        }
     }
   }();

问题是在调用callback()之前,可能会调用Prototype并且它会意外地使用'$'已被jQuery覆盖。

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

推荐答案

您可以控制库的加载顺序。首先加载jQuery库(通过在< head> 中设置该脚本节点,然后立即调用 $。noConflict()在允许加载其他脚本之前。

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.

这篇关于构建一个没有$ dollar符号的自定义jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆