2

I have a page with a dynamic number of iframes. window.print() has to be called when iframes has loaded (ie. has src).

How can this be handled elegantly in pure JavaScript without being to pedantic?

PHearst
  • 751
  • 6
  • 29

3 Answers3

1
function getLoadedFrames () {

    var frames = document.getElementsByTagName( 'iframe' ), // Get all iframes
        loadedFrames = [], i;

    for ( i = 0; i < frames.length; i++ ) {
        /*
            If iframe has a src attribute, that attribute has a value AND
            that value is not equal to the current window location (leaving src
            blank seems to return the current location instead of empty string)
            then add the frame to the loadedFrames array.
        */
        if ( frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src !== window.location.href ) {
            loadedFrames.push( frames[ i ] );
        }
    }

    return loadedFrames; // An array of your 'loaded' frames
}
Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
  • Heavy on the if conditions, but it's kind of a weird problem so this is a reasonable solution. – PHearst Oct 06 '12 at 12:07
  • @kevin : is there a way to check if iframe has src or not ...........if(iframe_loaded){do_nothing...}else{load the iframe src} – Hitesh Jan 02 '14 at 07:39
0

You could do

function areAllIframesLoaded() {
  var frames = document.getElementsByTagName( 'iframe' )
  return Array.prototype.slice.call(frames).reduce(function(p, c) {
    return p && c.src && c.src.length > 0 && c.src !== window.location.href
  }, true);
}

This will iterate over all the iframes and return true or false on whether or not all of them have a src defined.

saml
  • 6,702
  • 1
  • 34
  • 30
0

Not quite sure if that's what you want, but perhaps it helps:

window.addEventListener("DOMContentLoaded", function(){
    // Get all iframes as soon as DOM has loaded
    var iframes = document.getElementsByTagName("iframe");
    for (var i = 0, l = iframes.length; i < l; ++i) {
        // Add event handler to every iframe
        iframes[i].onload = function(){
            // Execute window.print() when iframe has loaded
            window.print();
        };
    }
});

This works without checking the src attribute, because if a iframe doesn't have a src, the onload event will never be fired.

Note that this won't work in IE; see this answer on SO for an equivalent to jQuery's $(document).ready...

Community
  • 1
  • 1
Aletheios
  • 3,960
  • 2
  • 33
  • 46
  • Thanks, but to support IE, it gets _kind_ of pedantic ;-) – PHearst Oct 06 '12 at 12:03
  • But in general cases, it's better checking the onload, as I'll have to add some additional loadtime is required for each iframe even though it has src. – PHearst Oct 06 '12 at 12:24
  • Those were my thoughts too. Perhaps you should consider being a bit pedantic in this case... ;) – Aletheios Oct 06 '12 at 12:49