Created
December 11, 2017 17:42
-
-
Save nleush/23ea25bfb2f46a67bc919fc5e0e874a5 to your computer and use it in GitHub Desktop.
'onload' event example for Iframely iframe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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