Waiting cache events for img

Posted by Gladiator2043 on Sun, 05 Jan 2020 12:42:28 +0100

Demand:

Ensure that the printing method is executed after all pictures are loaded successfully

Implementation of final code:

printMail = () => {
    this.btnDisplay='none';
    //Get the window object of iframe
    let iframe = document.getElementsByClassName('wea-email-content-iframe')[0].contentWindow;
    let img_length = iframe.document.getElementsByTagName('img').length;
    let img_success = 0;
    let img_erro = 0;
    let img_all = 0;
    let images = iframe.document.getElementsByTagName('img');
    if(img_length === 0){
      setTimeout(()=>{
        window.print();
        this.btnDisplay='block';
      },100);
    }else if(img_length > 0){
      for(let image of images){
        let oneImg = new Image(); 
        oneImg.src=image.src;
        oneImg.onload=()=>{
          img_success++;
          img_all ++;
          if(img_all == img_length){
            setTimeout(()=>{
              window.print();
              this.btnDisplay='block';
            },100);
          }
        };
        oneImg.onerror=()=>{
          img_erro++;
          img_all ++;
          if(img_all == img_length){
            setTimeout(()=>{
              window.print();
              this.btnDisplay='block';
            },100);
          }
        };      
      }
    }
  }

Thus, today's exploration of knowledge points begins [analyze the knowledge points in the code HA]:

1. Create an Image object: var a=new Image(); define the SRC of the Image object: a.src = "xxx.gif"; this is equivalent to caching a picture for the browser.

Note: the src attribute must be written after onload, otherwise the program will make an error in IE. (just saw it, ran to fix the bug...)

You can check whether the Image is loaded through the complete attribute of the Image object (each Image object has a complete attribute when the Image is in the

During the loading process, the value of this attribute is false. When any one of the events onload, onerror, onabort occurs, it means the end of the image loading process (regardless of success

Failed). The complete property is true.)

var img = new Image();  
img.src = oImg[0].src = this.src.replace(/small/,"big");  
oDiv.style.display = "block";  
img.complete ? oDiv.style.display = "none" : (oImg[0].onload = function() {oDiv.style.display = "none"})  

Note:

Popular browsers such as ie Firefox support onload events of Image objects.

ie8 and below, opera does not support onerror events

Topics: Attribute IE Firefox