加载Facebook像素异步

时间:2017-07-02 17:11:33

标签: javascript facebook

我正在加载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中并继续检查,直到外部脚本完全加载,但我想知道是否有更好的方法来实现它。

1 个答案:

答案 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');

})();

有一些可能导致错误的潜在原因:

  1. 在浏览器外运行脚本,破坏窗口变量的环境。

  2. 在浏览器上运行代码但冻结windowObject.freeze(window))导致fbqundefined

  3. Object.seal(window)也是freeze()。它会阻止将新属性添加到window

  4. 创建本地范围命名 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();