Multiple Iframes sending ONE request to the same S

2019-08-11 03:41发布

问题:

I was wondering if there was a way to have say 3 iframes load the same resource (http://myservice.php) with ONLY ONE request from the iframe. The myservice.php returns an Html Document and the browser should somehow load the html without reloading everything 2 additional times including CSS and JS in the loaded HTML document. In other words, is it possible with ONLY 1 request sent from the 1st iframe to load the HTML document from myservice.php, and have the other 2 iframes load the same html without sending additional http requests.

<iframe id="iframe1" src="myservice.php"></iframe>//should send only request
<iframe id="iframe2" src="myservice.php"></iframe>//use the already loaded data without sending an additonal http request
<iframe id="iframe3" src="myservice.php"></iframe>

I have thought about storing the html with jsonp(to avoid cross domain problems) and store it in a variable but i am not sure if it s more efficient than having the default way with multiple iframes sending multiple http requests to my .php. Also, the the size of the html is also heavy which i think can affect the browser.

回答1:

I think you need to use javascript for this.

Take your frames and give each of them a different id:

<iframe name="iframe1" id="f1" src="old.html"></iframe>
<iframe name="iframe2" id="f2" src="old.html"></iframe>
<iframe name="iframe3" id="f3" src="old.html"></iframe>

Call a function:

<a href="#" onClick="multipleFrames('new.html');">change iframes</a>

It would be best to pass the URL in the function. This makes your code more reusable.

Then make a function to which you pass the url (u).

function multipleFrames(u){ //url
    var frames=window.frames;
    for (var i=1; i<3; i++){

        var frame="f"+i;
        document.getElementById(frame).src = u;
    }
}

If you have a differing amount of iframes in different places you could pass the number of iframes as well

<a href="#" onClick="multipleFrames('new.html','3');">change iframes</a>

 

     function multipleFrames(u,n){ //url, number of iframes
                var frames=window.frames;
                var total=n+1;
                for (var i=1; i<total; i++){

...
}