Karan Singh Dhir
Karan Singh Dhir

Reputation: 751

How to loop through different iframes?

I want to put the iframes in a loop and have the next one waiting in queue while the first one loads, parses and renders. The second iframe only loads when the first one has been rendered successfully.

I've been using a for loop and tested setTimeout, and discovered that the timeout was only executed when the for-loop was over.

var displayFrames = document.getElementById("displayframes");

for (var i = 0; i < filenames.length; i++) {
  var frame = document.createElement("iframe");
  frame.src = "templates/" + filenames[i];
  frame.width = (window.innerWidth/3);
  frame.height = (window.innerHeight/2);
  displayFrames.appendChild(frame);
};

Could you suggest me any better way of handling this problem?

Upvotes: 0

Views: 452

Answers (1)

Rikard Askel&#246;f
Rikard Askel&#246;f

Reputation: 2932

Something like this maybe using the iframe onload event to trigger the next load?

var displayFrames = document.getElementById("displayframes");

var fileNameCounter = 0;

var loadIframe = function() {

    if(fileNameCounter >= filenames.length - 1)
        return;

    var frame = document.createElement("iframe");
    frame.src = "templates/" + filenames[fileNameCounter];
    frame.width = (window.innerWidth/3);
    frame.height = (window.innerHeight/2);
    displayFrames.appendChild(frame);

    fileNameCounter++;

    frame.onload = function() {
        loadIframe();
    }
}

loadIframe();

Upvotes: 1

Related Questions