I am currently creating a page where upon clicking a link an iframe is inserted into a div and it's contents loaded. I do this using the following jQuery call:
$('#mydiv').html('<iframe src="sourcelink.html" frameborder="0" width="760" height="2400" scrolling="no"></iframe>');
Sometimes the source content loads very slowly and, as a result, it looks like nothing is happening. I would like to have a simple loading animation while the content is loading while the iframe's content loads. When the iframe finishes loading it's content should pop in and the loading animation should go away.
I've been considering a couple ways I could do this (e.g. having a separate loader div to simply swap the two in and out) but I'm not sure of what the 'best' approach to solving this problem is. Perhaps I shouldn't be using .html()? I'm open to suggestion if there is a more correct solution.
If you're hosting the page and the iframe on the same domain you can listen for the iframe's Window. DOMContentLoaded event. You have to wait for the original page to fire DOMContentLoaded first, then attach a DOMContentLoaded event listener on the iframe's Window .
Use the iFrame fallback embed The fastest way to load an embedded form is by using the iframe fallback method as outlined in the fallback documentation. If you go with this method, make sure you review the gotchas in the linked documentation to ensure this approach is right for you.
Definitely iframe affects the page load performance and also it is not recommended to use iframe for many page security issues perspective. SEO companies strongly discourage iframes.
Is there any reason you can't listen to the onload
event of the iframe itself? It should fire after the child content has loaded.
Something like this:
showLoader();
$('#mydiv').html('<iframe src="sourcelink.html" frameborder="0" width="760" height="2400" scrolling="no"></iframe>');
$('#mydiv iframe').load(function() { hideLoader(); }
So In my case doing the following did for me..
The HTML
<iframe id="ifrmReportViewer" src="" frameborder="0" style="overflow:hidden;width:100%; height: 1000px;"></iframe>
and I was loading the iFrame on button of a click, so here is the JS
$(document).ready(function () {
$('body').on('click','#btnLoadiFrame',function () {
ShowLoader();
$('#ifrmReportViewer').attr('src', url);
$('#ifrmReportViewer').load(function () {
HideLoader();
});
});
});
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