Reputation: 51937
I'm loading the Facebook pixel and getting an error because the script isn't loaded when the call is made. This is what it looks like:
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');
}
Problem is that fbq isn't initiated when the code runs. Now I know I could wrap the problem code inside a setInterval
and keep checking until the external script is fully loaded but I'm wondering if there's a better way to do it.
Upvotes: 1
Views: 7548
Reputation: 13489
I tried to reproduce this problem but in vain. Your code works perfectly.
fbq
is appended syncronously (So no need to timeout
) to window
and will be called normally. Check yourself:
(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');
})();
There are some potential reasons that may produce your error:
Running the script outside the browser, An env that ruined the window variable.
Running code on browser but with a freezed window
(Object.freeze(window)
) causes that fbq
will be undefined
So also Object.seal(window)
like freeze()
. It will prevent new properties from being added to window
Creating a local scope named window
variable will cause fbq
to be 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();
Upvotes: 4