ga.js
Google アナリティクスを使用してページ、イベントなどを追跡するカスタム ソリューションを実装しています。Google アナリティクスも使用し、重複している複数の利害関係者がいる環境で作業しているため、二重インクルードを回避するためにライブラリが既に含まれているかどうかを確認したいと思います。可能性です。
src
最初は、属性を探して、現在のすべてのスクリプトを循環させることを考えました:
// load the Google Analytics library only if it has not been already loaded:
var gaScripts = 0; // number of ga.js scripts in the current document
var scripts = document.getElementsByTagName('script');
for (var i in scripts) {
// go through all the scripts:
if (typeof(scripts[i].src) !== 'undefined' && scripts[i].src.split('?')[0].match(/ga\.js$/)) {
// update the counter if ga.js has been found:
gaScripts++;
}
}
if (gaScripts === 0) {
(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);
})();
// update the counter:
gaScripts++;
} else if (gaScripts > 1) {
// the ga.js library has been loaded more than once, log this error:
if (window.console) {
console.log('Warning: the ga.js script has been included ' + gaScripts + ' times in the page');
}
}
それは機能し、複数のインクルードの潜在的なエラーもログに記録します。_gaq
次に、スタックのオブジェクト プロトタイプをチェックすることで、よりスマートに考えました。
with (window) {
if (_gaq instanceof Array) {
// not loaded, so include it...
} else {
// it's been included
}
}
_gaq
オブジェクトがまだga.js
ライブラリによって初期化されていない場合、オブジェクトは単純な配列であるため、最初の条件は true です。初期化されると、オブジェクトとして上書きされ、Array プリミティブ オブジェクトのインスタンスではなくなります。
欠点
私は壮大な問題について疑問に思っています:ライブラリが含まれているが、非同期で呼び出されたためにまだDOMにロードされていないwindow.onload
場合、ソリューションを同期コード(配置された時点で評価)として実装すると、いずれにせよ二重インクルードが発生します。ga.js
そのため、DOMContentLoaded
イベントをトリガーして、その間に 2 つのソリューションのいずれかを呼び出す必要があります。
このトピックに関する同様の質問をWebで検索しましたが、公式のGAドキュメントにはそれに関する情報がなく、人気のあるリソースの結果もそれを扱っていないようです.
私が私に提起したもう 1 つの質問は、二重インクルードが問題であるかどうかです。純粋な技術的な観点から、Google アナリティクスはこの種のユーザー エラーを予測して管理できると考えました。 ?)。しかし、ユーザーの観点からすると、無駄な 2 回目の HTTP リクエストの時間は煩わしく、できれば避けたいものです。
誰かがこの問題に直面したか、何か提案がありましたか?