oma0256
oma0256

Reputation: 103

Rendering multiple iframes one after the other

I have an array of urls that I want to use to render iframes on a page. My goal is to have contents of an iframe to display before displaying the next iframe, the process continues until when I have rendered iframes for all the urls in my array. Not sure what I'm doing wrong, below is a script I have written to handle this. Works well with a single url, however for multiple urls it tries to fetch all the contents from all the urls before rendering any iframe on the page.

<script>
    get('endpoint to fetch the urls').then(data => { // makes api request to fetch the urls.
        const lti_launch_urls = data['lti_launch_urls'] 
        lti_launch_urls.forEach((launch_url, index) => {


                const iframe = document.createElement('iframe')
                iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
                iframe.width = "100%"
                iframe.frameBorder = "0"
                iframeId = "iframe-" + index
                iframe.id = iframeId
                iframe.src = launch_url
                document.body.appendChild(iframe)
                iframe.contentWindow.postMessage(style, "*");
        })

    })
</script>

Upvotes: 1

Views: 1237

Answers (1)

Taplar
Taplar

Reputation: 24965

I would suggest something like the following. Pull your logic into a reusable method that performs the iframe generation that takes an index. Call it starting at index 0 to show the first iframe. Then, once the iframe has a load event encountered, call the method again with the next index to perform the logical iteration.

    const lti_launch_urls = data['lti_launch_urls'];
    const loadNextIframe = index => {
      if (index >= lti_launch_urls.length) return;

      const launch_url = lti_launch_urls[index];
      const iframe = document.createElement('iframe');

      iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
      iframe.width = "100%";
      iframe.frameBorder = "0";
      iframeId = "iframe-" + index;
      iframe.id = iframeId;
      iframe.src = launch_url;

      iframe.addEventListener('load', () => loadNextIframe(++index));

      document.body.appendChild(iframe);
      iframe.contentWindow.postMessage(style, "*");
    };

    loadNextIframe(0);

Upvotes: 2

Related Questions