Prevent loading the content of a hidden iframe
Asked Answered
M

2

14

I have many hidden <div> tags, with (display: none), that I call upon when I want to load a jQuery modal. Each of these <div> tags contain an <iframe> which calls a different page.

In order to not make my page load painfully slowly, I am wondering if there is a way to prevent the <iframe> from loading the page, until I call the <div> in the modal?

Maximalist answered 14/2, 2013 at 5:18 Comment(0)
K
17

You can load the iframes after html being rendered by giving empty src in html of iframe and later assigning src by jquery / javascript.

Html

<iframe id="iframe1" ></iframe>

Javascript, iframe could be loaded on some action like button click

document.getElementById('iframe1').src="/default.aspx";

As kern3l said, we can add data attribute in iframe for holding src instead of hard coding.

Html

<iframe id="iframe1" data-frameSrc="/default.aspx"></iframe>

Javascript

ifrmame1 = $('#iframe1')
ifrmam1.src = ifrmam1.data("frameSrc");

You can also make a new frame in jquery and assign src, this will load the page with blank frame.

$('<iframe>', {
   src: '/default.aspx',
   id:  'myFrame',
   frameborder: 0,
   scrolling: 'no'
   }).appendTo('#parentDivId'); 

OR

var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="myFrame";
iframe.setAttribute("src", '/default.aspx');
document.getElementById("parentDivId").appendChild(iframe);
Kurr answered 14/2, 2013 at 5:20 Comment(2)
You can do it much better by storing src in data-src attribute and reading from it when need be. Then you don't store data in your javascript (which is better).Oversee
This solution is mentioned a lot on the net but it has a big flow. If you don't set src browser will set it to "about:blank". When you later show your modal and set another src it will load and everything will be ok until your user presses back button in their browser and this will return your still displayed modal iframe to "about:blank". Best option is to dynamically create the whole iframe element.External
F
3

Just use one iframe:

<iframe id='page' src=''></iframe>

then assign src on each click of the button/link:

suppose this is the html:

<ul>
  <li><a href='myfolder/myPage1.html'>Page 1</a></li>
  <li><a href='myfolder/myPage2.html'>Page 2</a></li>
</ul>

then jquery:

$('ul li a').click(function(e){
   e.preventDefault();
   $('#page').attr('src', $(this).attr('href'));
});
Fatma answered 14/2, 2013 at 5:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.