Googleコードで使用されている識別子を使って変数を宣言しても、同じことが起こりますが、ページ上の他のスクリプトを簡単に破壊する可能性があります。
変数をクロージャでラップすると、変数のスコープが匿名関数になり、グローバルスコープにリークすることはありません。例えば
、新しいスコープでこの例を考えてみます。それなし
var ga = "something important for my script"; // Not overwritten in this scope
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
そして、この例:
var ga = "something important for my script"; // Overwritten!
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
これは、グローバル名前空間を 'ga'と' s'変数で汚染しないようにするためです。 – AKX