You need to lazy-load a script tag that modifies the DOM through a placeholder <div>. By using this script, the request is made and the content rendered inside the placeholder only when the placeholder becomes visible in the viewport.
Useful for 3rd party scripts that have two elements:
- A
divthat receives content through a script. - An async
scripttag that request the script necessary to render content on the placeholder.
<div data-spklw-widget="widget-7777777777777"></div>
<script type="text/javascript" async src="//widgets.sprinklecontent.com/v2/sprinkle.js"></script>The snippet above becomes:
Syncronous
<div id="strossle" data-spklw-widget="widget-7777777777777"></div>
<script>
lazyScript('strossle', '//widgets.sprinklecontent.com/v2/sprinkle.js', 100);
</script>No need for 'on doc ready' check as script is loaded right after the element it depends on, but this assumes that lazyScript was included synchronously and is therefore defined.
Asyncronous
<div id="strossle" data-spklw-widget="widget-7777777777777"></div>
<script>
(function () {
var intervalCounterStrossle = 0;
if (window.lazyScript) {
window.lazyScript('strossle', '//widgets.sprinklecontent.com/v2/sprinkle.js', 100);
} else {
console.log('[lazyScript]: "lazyScript" is undefined at this point, so we cannot load Strossle. Attempting to load it again...');
var loadStrossleInterval = window.setInterval(function () {
intervalCounterStrossle++;
if (window.lazyScript) {
window.clearInterval(loadStrossleInterval);
window.lazyScript('strossle', '//widgets.sprinklecontent.com/v2/sprinkle.js', 100);
} else if (intervalCounterStrossle > 50) {
window.clearInterval(loadStrossleInterval);
console.log('[lazyScript]: Strossle timed-out after attempting to load it through "lazyScript", which is still undefined');
}
}, 100);
}
})();
</script>No need for 'on doc ready' check as script is loaded right after the element it depends on.
If lazyScript was included asynchronously and isn't defined by the time it's called, we will continue to attempt loading it for another 5 secs (in this case). It will eventually fail after the timeout, and a console error will explain what just happened.
Though unrelated to the challenge at hand, the principle applied above could be used to determine 'on element ready'. However an inline script tag right after the element (like it was done in the examples above) enables us to skip checking for the element's existence, since it's guaranteed to be there.