iframe hosted on CloudRun not firing onLoad event in React JS

55 views Asked by At

I have an iframe embedded in a webpage. Sometimes the iframe takes a while to load, sometimes it loads instantaneously. I want to display a spinning wheel animation while the iframe is loading. I am using the onLoad event, but it doesn't seem to fire at all. My debug message is never logged and the spinning animation displays endlessly. What am I doing wrong and what's a robust way to detect when the iframe has loaded?

I am using React + next.js + tailwind css.

'use client'
import { useState, useEffect } from 'react';

const GradioPage = () => {
  const [loading, setLoading] = useState(true);
  const demoUrl = 'https://mydemo';

  return (
    <div className="mt-24 flex justify-center items-center h-screen">
      {loading && (
        <div className="flex justify-center items-center w-full h-full">
          <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-gray-900"></div>
        </div>
      )}
      <iframe
        src={demoUrl}
        className={`w-full h-full ${loading ? 'hidden' : ''}`}
        title="Gradio Demo"
        onLoad={() => {console.log("LOADED"); setLoading(false);}}
      ></iframe>
    </div>
  );
};

P.S.

  • It doesn't seem to be related to my display logic since if I manually set loading to false after a certain timeout, the spinning wheel disappears and the iframe shows up.
  • I am testing in Chrome
  • I can't control the iframe content

UPDATE: The iframe is an app hosted on GCP CloudRun. CloudRun is configured to scale down to 0 nodes, so if no requests are made for a while, the container is deallocated and has a cold start next time. Debugging showed that onLoad fires consistently on cold starts, but subsequent loads don't fire the event. Confirmed that this is not related to browser caching since the problem happens in incognito windows and in a browser with clear cache. Furthermore, changing the iframe to a youtube source, works consistently every time. So the problem seems to be related to CloudRun.

Since, I have control over CloudRun configuration, is there something I can change to make it fire onLoad consistently or use another way to reliably detect when the iframe has loaded?

1

There are 1 answers

1
Sandeep M On

Can you try the below link and check it out.I haven't made any css changes to the loader animation, I just copy pasted the code from tailwind, so you can change it. Regarding why it doesn't work, it could be that you might not be using the correct embedded link, which wouldn't let the onload event to trigger.

CodeSandbox