Lazy load Tracking js in iframe only when iframe is in view
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

We have a 3rd party widget which we load in partner sites to show their audience some of their syndicated content. In this widget we need to load GTM and some pixel tracking but we only want that to fire when the iframe is actually in view. As we understand the end user will just embed our script in their site so we don’t control a lot of external variables but we don’t want to load GA/ GTM until the widget is actually being seen. (It’s often in the footer so we can’t assume page load of the host is a view for us)

Here is our widget code

And here is a demo of it

The goal would be to modify what we have to basically lazy load the tracking till the iframe is in view

can you share the code to be embedded ?, if the code is only an iframe that would be a problem due to same origin policy we can get around that by adding some js on the client side and use postMessage to communicate with the iframe
ahmedengu 3 months ago
Sure - all of the code is above with example but the embed code looks like this
Qdev 3 months ago
thanks, gonna prepare a pull request for you
ahmedengu 3 months ago
awarded to Wuddrum

Crowdsource coding tasks.

2 Solutions


You may check my pull request here:

kindly feel free to address any issues you may find or and additions, also if you want you can share the trackers code to make them load for you.

the current behavior when you scroll you gonna see a console message says:
and a corresponding one from the iframe says:
received: onScroll

you may test here:

to add GTM just replace the content on the receiveMessage function with:

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

the same thing could be done with GA:

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');

also on the receiveMessage function you may need to check for the event.origin or as a security check or to prevent collisions but am not aware if you are using any other postMessage or what origins you may want to restrict to, however a simple check would be like this:

function receiveMessage(event) {
    if ( == "s") {
        console.log("received: " +;

the code can be compressed to this form that’s 366 characters, totaling 366 bytes (counting the script only total up to 546) and still supports all browsers:

 <script>!function(t,o,i){t.addEventListener("message",function(e){var;n+1<2||(o.getElementById(i).style.height=n+"px")}),t.onload=function(){var e=o.getElementById(i);function n(){t.innerHeight>e.getBoundingClientRect().top&&(o.removeEventListener("scroll",n),e.contentWindow.postMessage("s","*"))}o.addEventListener("scroll",n),n()}}(window,document,"NewsWidget");</script>
<iframe id="NewsWidget" src="//" width="100%" frameborder="0" scrolling="no"></iframe>

Best regards,


do you mind making a codepen or similar. this demo link is rendering weird and its difficult to work through whats going on with it?
Qdev 3 months ago
sure, gonna prepare a codepen in a minute
ahmedengu 3 months ago
you may test here , gonna update my PR too
ahmedengu 3 months ago
you may find the compressed code in the dist folder , also the full version could be found on the root directory you may use to compress the code easily after adding the GA/GTM code
ahmedengu 3 months ago
I'd argue that changing your solution to imitate mine more closely, while omitting a bunch of logic is not the best idea.
What if there's another script or extension that's posting integer messages to the page? You'd now get random widget resizing.
What if the user is refreshing, using browser's back button or is auto-scrolled bellow the widget? Tracking still gets fired, even if the widget is not in viewport.
Same goes for pages that flow horizontally or pages that offload/store contents to sides.
Can you be certain that by assigning window.onload you won't overwrite or get overwritten by another script on the page that also might use it?
Wuddrum 3 months ago
You are totally correct, i apologize for doing that.
ahmedengu 3 months ago
Winning solution

Hey Qdev, here are my 2 options for the solution:

Option A



Widget code for testing:

<iframe id="NewsWidget" src="//" width="100%" frameborder="0" scrolling="no"></iframe>

This solution is using IntersectionObserver. Because of how it works, all of the implementation (17 lines of code) can reside in embed itself, without the need of increasing the size of widget code.

This is a more reliable and robust solution over Option B.

The major problem with this approach is browser compatibility. The API is currently not available in IE and Safari browsers. As a fallback for those browsers I've made the tracking call to fire on page load. The good news is that Safari has this API implemented in the next version of browsers (both Mac and iOS), so only IE will be left unsupported.

Option B


Widget code for testing:

<script>!function(c,d,f,g){d("message",function(a){""===a.origin.split("://")[1]&&(f(g)"px")});d("load",function(){var a=f(g),e=function(){var b=a.getBoundingClientRect();0<b.right&&b.left<c.innerWidth&&0<b.bottom&&<c.innerHeight&&(c.removeEventListener("scroll",e),a.contentWindow.postMessage({v:1},"*"))};d("scroll",e);e()})}(window,window.addEventListener.bind(window),document.getElementById.bind(document),"NewsWidget");</script>
<iframe id="NewsWidget" src="//" width="100%" frameborder="0" scrolling="no"></iframe>

This solution is using the standard getBoundingClientRect(), that's used for these problems, when browser compatibility even with IE is required. Unfortunately this code can't be run from within the embed itself, so the widget size suffers and is not as lean as Option A (161 bytes vs 460 bytes).

Another possible problem with this approach is that if the widget is hosted on some kind of scrolling element, the visibility calculations might start acting unreliably.

Both options work on both - vertically and horizontally flowing pages (or pages that might hide their elements on sides).

Edit: Slimmed down the widgets for both options a bit. A few more bytes can be saved here and there, but it wouldn't make much of a difference.

hey there I am having a tough time testing on the downloaded code. seems to be looking like this for me - I get similar issue with option B. Thanks!
Qdev 3 months ago
It's happening because widget.js is filtering the messages by their origin (to not accidentaly resize the iframe if the message comes from the wrong origin).
Inside widget.js , on the line that reads if (e.origin.split('://')[1] !== '') return;, you must change the domain to one, where embed.html is hosted on.
Looks like for this particular case the line should read if (e.origin.split('://')[1] !== '') return;
Wuddrum 3 months ago
For testing purposes, if you don't know what domain you might get, or they change often, you can just comment out the line.
Wuddrum 3 months ago
View Timeline