I have a few iframes on my homepage at the bottom (http://www.binarycontrast.com), where one is randomly selected on page load. The code I'm using below works, but the iframes load really slowly. What the code does is generate a random iframe to display on page load. I actually got the code from another question on here regarding loading random images on page load, and I just tweeked it to what I needed.
If I have a single iframe on the page it loads really quickly, but for some reason using this code slows it down a lot, so I want a way to speed up the iframe loading time whilst using some script to randomly choose one to display.
An alternative method or help with the code I have would be really appreciated.
Please see the below code:
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/24Option" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/OptionFair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/StockPair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
And the script used to make it work:
$(window).load(function(){
var divs = $("iframe.random-iframe").get().sort(function(){
return Math.round(Math.random())-0.5; //random so we get the right +/- combo
}).slice(0,1)
$(divs).appendTo(divs[0].parentNode).show();
});
And the css:
iframe.random-iframe { display: none; }
Thanks for any help in advance.
I think the Problem ist that you load all the iframes. Even the ones you don't need. You should only hold your Urls (Not the whole iframe tags) and the make a random select for one of the urls. Only then create a Iframe tag with the selected url.
something like this:
function getRandomUrl(urls) {
var minIndex = 0;
var maxIndex = urls.length - 1;
var randomIndex = Math.floor(Math.random() * (maxIndex - minIndex)) + minIndex;
return urls[randomIndex];
}
var urls = [
"url1",
"url2",
"url3"];
var randomSelectedUrl = getRandomUrl(urls);
$("#hereComesTheIframeInto").html(
"<iframe class='random-iframe' src='" + randomSelectedUrl + "' width='100%' height='700' frameborder='0' scrolling='yes' seamless='seamless'></iframe>");
<div id="hereComesTheIframeInto"></div>
I Hope you get the point. I didn't finish it completely for you.
EDIT: eradicated error. (I have composed the strings with "&" before but in Javascript you have to do this with "+") Sorry for this. =(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With