lazy load iframe (delay src http call) with jquery

2019-02-01 10:35发布

问题:

I am looking for something similar to jQuery image lazy load plugin, but for iframes.

回答1:

This worked for me.

var iframes = $('iframe');

$('button').click(function() {
    iframes.attr('src', function() {
        return $(this).data('src');
    });
});

iframes.attr('data-src', function() {
    var src = $(this).attr('src');
    $(this).removeAttr('src');
    return src;
});

jsFiddle.



回答2:

A similar question was recently posted specific to iFrames with Twitter Bootstrap-based tabs, which I answered using a technique I'm calling Lazy Loading of iFrames. The js/jquery is as follows; see the full code including html markup in the fiddle or on my response to the OP:

<script>
$('#myTabs').bind('show', function(e) {  

// identify the tab-pane
paneID = $(e.target).attr('href');

// get the value of the custom data attribute to use as the iframe source
src = $(paneID).attr('data-src');

//if the iframe on the selected tab-pane hasn't been loaded yet...
if($(paneID+" iframe").attr("src")=="")
{
    // update the iframe src attribute using the custom data-attribute value
    $(paneID+" iframe").attr("src",src);
}
});
</script>


回答3:

You could always intialize the src attribute to about:blank and then when your click event fires, set the src attribute to the URL you want to navigate to.



回答4:

Can you set the src to about:blank? Like this?

http://jsfiddle.net/MaUfH/



回答5:

If you want to do this in WordPress

Here is an automatic, request reducing, solution

In WordPress plugin form

Here is a WordPress plugin you can download and manually install via the WordPress plugin repository. I created this today just to handle this situation. No changes to content are needed, this works automatically once activated on any and all iframes.

https://wordpress.org/plugins/lowermedia-iframes-on-demand/