質問

At first, i tought that Zepto only defined a "Zepto" global variable if $ wasn't available. So, i decided to make those tests:

First Fiddle - Pure Zepto

Second Fiddle - Zepto + jQuery

Source

HTML

<div id="first-global">
</div>
<div id="second-global">
</div>

JS

var first = document.getElementById('first-global'),
    second = document.getElementById('second-global');

first.innerHTML = $;
second.innerHTML = Zepto

Code is the same at both, only thing that changes is the framework used.

So, as you can see in first fiddle, Zepto initializes both variables, $ AND Zepto. Isn't that(Define two identical global variables) a bad practice? There would be a way to define Zepto global only IF $ wasn't available?

役に立ちましたか?

解決

From zeptojs.com:

"Zepto will only set the $ global to itself if it is not yet defined. There is no Zepto.noConflict method."

So it would depend on the order of including these libraries. If jQuery is included first then Zepto won't overwrite the global $. If Zepto is included first, then you could use jQuery.noConflict to make $ point to Zepto.

And no, it's not a bad practice - $ is the short and easy alias, while the library also has its full name as a global. BTW I hope it's purely theoretical question - why would you include both libraries on one page? ;)

$ is less reliable than library's own name (as proved by your question). Many libraries may try to set global $ while it's less probable that a variable like jQuery or Zepto will get accidentally overwritten.

To be sure what's behind $ you may use this pattern:

(function($){
   $('selector').doSomething();
}(library));

where library is the other global variable besides $ you want to reference (Zepto or jQuery).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top