On this page
Monitor, code on it and the open HTML tag iframe.

Implement “Please wait” message while iframe is loading using JavaScript

Improve user experience by implementing a "Please wait" message during iframe loading with JavaScript.

When embedding content using iframe (inline frame), users may experience delays while the iframe loads, especially if the content is from a slow server or a third-party site. During this period, users may perceive the application as unresponsive. To mitigate this issue, a Please wait message or an animated loading indicator can be displayed, depending on the design requirements.

Let’s explore the method to implement Please wait message for the iframe using TypeScript, a superset of JavaScript.

Easy steps to implement a Please Wait message

To display a Please wait message while an iframe is loading, we’ll utilize TypeScript and CSS. The CSS will style the message container ensuring it is visually appealing and we’d make it accessible to everyone, including screen reader users.

The code below uses TypeScript and CSS to achieve this.

“Please wait” implementation for the iframe
<style>
.iframe-container {
  position: relative;
  /* Example width of the container that matches iframe width, if needed
  width: 700px;
  */
}

.iframe-busy-indicator {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  left: 50%;
  padding: 20px;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}
</style>

<script>
class BusyIndicatorComponent {

  private createBusyIndicator(iframe: HTMLIFrameElement): void {
    const busyIndicator: HTMLDivElement = document.createElement('div');

    busyIndicator.ariaHidden = 'true';
    busyIndicator.className = 'iframe-busy-indicator';
    busyIndicator.textContent = 'Loading. Please wait.';

    const iframeContainer: HTMLDivElement = document.createElement('div');

    iframeContainer.className = 'iframe-container';

    iframeContainer.appendChild(busyIndicator);

    const clonedIframe: HTMLIFrameElement = iframe.cloneNode(true) as HTMLIFrameElement;

    clonedIframe.dataset.title = iframe.title || '';
    clonedIframe.title = 'Loading. Please wait.';

    iframeContainer.appendChild(clonedIframe);

    iframe.parentNode.replaceChild(iframeContainer, iframe);

    const stopIframeBusyIndicator = () => {
      busyIndicator.remove();

      if (clonedIframe.dataset.title.length > 0) {
        clonedIframe.title = clonedIframe.dataset.title;
      } else {
        clonedIframe.removeAttribute('title');
      }
    };

    clonedIframe.addEventListener('load', stopIframeBusyIndicator, { once: true });
  }

  private initBusyIndicators(): void {
    const iframes: HTMLIFrameElement[] = Array.from(document.querySelectorAll('iframe'));

    if (iframes.length === 0) {
      return;
    }

    iframes.forEach(this.createBusyIndicator.bind(this));
  }

  public init(): void {
    if (document.readyState !== 'loading') {
      this.initBusyIndicators();
      return;
    }

    document.addEventListener('DOMContentLoaded', this.initBusyIndicators.bind(this));
  }
}
</script>

The code usage example

“Please wait” usage example
<script>
const busyIndicatorComponent: BusyIndicatorComponent = new BusyIndicatorComponent();

busyIndicatorComponent.init();
</script>

Understanding the code

The code simply search for all iframes, add container with the message Please wait and remove that container when the iframe content is loaded.

The { once: true } option in the addEventListener method simplifies code by automatically removing the event listener after a single trigger, preventing multiple executions, improving code readability and memory usage, making it ideal for initialization tasks like one-time Please wait message.

Workable example

Tips for enhancements and important considerations

While the basic implementation is straightforward, there are several enhancements and considerations to improve the user experience further:

  • Loading animation: instead of a static message, consider using a loading spinner or animation to make the experience more dynamic.
  • Performance loading: for better performance loading, consider lazy loading the iframe if it is not immediately visible on the page. This can be done by setting the loading attribute of the iframe to lazy.

    Example: <iframe id="myIframe" src="https://example.com" loading="lazy" style="width: 100%; height: 500px;" onload="onLoadHandler()"></iframe>

  • Container size: you can set the width and height of the iframe container to the same size as your iframe.
  • Error handling: implement error handling to manage scenarios where the iframe fails to load. This can include displaying an error message or retrying the load.
  • Cross-domain restrictions: if the iframe loads content from a different domain, you may encounter restrictions due to the Same-Origin Policy. This policy can prevent you from accessing the iframe’s content or detecting its loading state. However, using the onload event as shown above typically works without issues.
  • Create CSS using JavaScript: you can create CSS using JavaScript and keep whole class as a single code instead of having CSS in the external file. However, the benefits of creating CSS using JavaScript and keeping the whole class as a single code depend on the specific use case and requirements of your application. It’s essential to weigh the pros and cons and consider factors like performance, maintainability, and debugging complexity before making a decision.

Conclusion

The implementation of a Please wait message during iframe loading can significantly improve user experience by providing feedback during content loading times. This approach not only enhances usability but also contributes to a better user experience.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Is your site slow?

Discover performance bottlenecks to provide a better customer experience and meet your company’s revenue targets.