我正在加载Facebook像素并收到错误,因为在调用时未加载脚本。这就是它的样子:
function Load3rdPartyScripts() {
(function (f, b, e, v, n, t, s) {
if (f.fbq) return; n = f.fbq = function () {
n.callMethod ?
n.callMethod.apply(n, arguments) : n.queue.push(arguments)
}; if (!f._fbq) f._fbq = n;
n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
})(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);
fbq('init', 'XXXXXXXXXXXXX'); //problem here
fbq('track', 'PageView');
}
问题是代码运行时不启动fbq。现在我知道我可以将问题代码包装在setInterval
中并继续检查,直到外部脚本完全加载,但我想知道是否有更好的方法来实现它。
答案 0 :(得分:2)
我试图重现这个问题,但徒劳无功。您的代码完美无缺。
fbq
被同步附加(因此无需timeout
)到window
,并且会被正常调用。检查一下自己:
(function Load3rdPartyScripts() {
(function (f, b, e, v, n, t, s) {
if (f.fbq) return; n = f.fbq = function () {
n.callMethod ?
n.callMethod.apply(n, arguments) : n.queue.push(arguments)
}; if (!f._fbq) f._fbq = n;
n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
})(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);
fbq('init', 'XXXXXXXXXXXXX'); // No problem here!
fbq('track', 'PageView');
})();
有一些可能导致错误的潜在原因:
在浏览器外运行脚本,破坏窗口变量的环境。
在浏览器上运行代码但冻结window
(Object.freeze(window)
)导致fbq
为undefined
Object.seal(window)
也是freeze()
。它会阻止将新属性添加到window
创建本地范围命名 window
变量会导致fbq
成为undefined
function Load3rdPartyScripts() {
let window = {}; // Notice!
(function (f, b, e, v, n, t, s) {
if (f.fbq) return; n = f.fbq = function () {
n.callMethod ?
n.callMethod.apply(n, arguments) : n.queue.push(arguments)
}; if (!f._fbq) f._fbq = n;
n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
})(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);
fbq('init', 'XXXXXXXXXXXXX'); //problem here
fbq('track', 'PageView');
}
Load3rdPartyScripts();