Start codelab

Codelab Flow

What you will learn

L I Iframes in PWAs

In this codelab you will learn how to Progressively handle Iframes loading when your user is offline.

Making Iframes work offline in PWAs is not atleast possible for now but then, good user experience comes first. There are many options you can go for. But for this case, we have one which is more straight forward.

Approach : Once the DOM is loaded, check for connectivity status using javascript and render a custom offline alert message to the user.

Setting up

Below is the section element that should be holding your iframe and a div element where we shall display our offline alert message.

  <section class="load-iframe">
  <!-- iframe  -->
        <iframe> </iframe>
  </section> 
  <!-- offline text paragraph -->
  <div class="offline-alert"> </div>
Add your iframe inside the html markup above and create an empty app.loadIframe.js in your project and copy the javascript code snippet provided below.
 
  // Learn more at : https://pwafire.org
  let loadIframe = document.querySelector('.load-iframe');
  let offlineAlert = document.querySelector('.offline-alert');

  // once the DOM is loaded, check for connectivity status
  document.addEventListener('DOMContentLoaded', (event) => {
      if (!navigator.onLine) {
          const goOffline = () => {
              loadIframe.style.display = "none";
              offlineAlert.innerHTML = `<p>Whooah...could not load iframe 😞, 
              you need to be connected!</p>`;
          }
           goOffline();
      } else {
          offlineAlert.style.display = "none";
      }
  });
  
You can play live with the Glitch App below and try to go offline and see what happens.

What's next?

Take more codelabs here

Edit on Github