Skip to content

Instantly share code, notes, and snippets.

@nleush
Created December 11, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nleush/23ea25bfb2f46a67bc919fc5e0e874a5 to your computer and use it in GitHub Desktop.
Save nleush/23ea25bfb2f46a67bc919fc5e0e874a5 to your computer and use it in GitHub Desktop.
'onload' event example for Iframely iframe
var receiveMessage = function(callback) {
function cb(e) {
var message;
try {
message = JSON.parse(e.data);
} catch (ex) {
}
callback(e, message);
}
// Check if browser supports window.postMessage
if (window['postMessage']) {
if (window['addEventListener']) {
window[callback ? 'addEventListener' : 'removeEventListener']('message', cb, !1);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', cb);
}
}
};
function onIframelyIframeLoad(iframe, loadedCb) {
var loadCount = 0;
var timeoutId;
var loaded = false;
// Prevent double event call.
function loadedCbWrapper() {
if (loaded) {
return;
}
loaded = true;
clearTimeout(timeoutId);
loadedCb(iframe);
}
function iframeOnLoad(force) {
if (!force) {
// Iframely hosted + redirect = 2.
// Only target (redirect) = 1.
// Check attribute on load, because its set dynamically by embed.js.
var needLoadsCount = iframe.hasAttribute('data-direct') ? 1 : 2;
loadCount++;
// Skip first load of hosted widget.
if (loadCount !== needLoadsCount) {
return;
}
}
// Timeout for dimmed widgets, e.g. youtube.
setTimeout(function() {
loadedCbWrapper();
}, 200);
}
function iframeOnLoadEvent() {
// Call without 'force' param.
iframeOnLoad();
}
// Iframely onload event.
iframe['addEventListener'] ? iframe['addEventListener']('load', iframeOnLoadEvent) : iframe.attachEvent('onload', iframeOnLoadEvent);
// Fallback with timeout.
timeoutId = setTimeout(function() {
iframeOnLoad(true);
}, 10000);
// Hosted widget card will send 'widgetRendered' event when rendered.
receiveMessage(function(e, message) {
if (message
&& message.method
&& message.method === 'widgetRendered'
&& iframe.contentWindow === e.source) {
loadedCbWrapper();
}
});
}
// Test code.
var iframes = document.querySelectorAll('iframe');
iframes.forEach(function(iframe) {
onIframelyIframeLoad(iframe, function(iframe) {
console.log('loaded', iframe)
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment