Search code examples
javascriptsweetalert2

Sweetalert2 modal loads briefly before image appears in modal


I'm using Sweetalert2 to display a modal that has an image inside. Although it works fine, the modal without the image shows for a split second before the image appears. How can I wait until the image fully loads. Here's what I've tried that doesn't work: (loadPage is called when the page loads.)

    function loadPage() {
    var img = new Image();
    img.onload = function () { setTimeout(function () { getToast(); }, 5000); }
    img.src = "Images/Save.png";
}

function getToast() {
    const Toast = Swal.mixin({
        toast: false,
        showConfirmButton: true,
        confirmButtonText: 'close',
        timer: 6000,
        imageUrl: 'Images/Save.png',
        timerProgressBar: true,
        title: 'My message.',
    })
    Toast.fire({

    })
}

Solution

  • The way you're doing it should just work without any flicker. The image is downloaded, cached and on the subsequent requests it should be served from cache. I created a fiddle and could not reconstruct your described issue.

    Although I created an alternative approach saving the downloaded image as an dataURI and passing it to your SweetAlert instance. This way you can prevent accidentally downloading the image multiple times.

    function loadPage() {
    
        var img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = function() {
          var canvas = document.createElement('canvas');
          var ctx = canvas.getContext('2d');
          var dataURL;
          canvas.height = this.height;
          canvas.width = this.width;
          ctx.drawImage(this, 0, 0);
          dataURL = canvas.toDataURL('canvas');
          setTimeout(function () { getToast(dataURL); }, 1000);
          canvas = null;
        };
      img.src = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
    }
    
    function getToast(dataURL) {
        const Toast = Swal.mixin({
            toast: false,
            showConfirmButton: true,
            confirmButtonText: 'close',
            timer: 6000,
            imageUrl: dataURL,
            timerProgressBar: true,
            title: 'My message.',
        })
        Toast.fire({
    
        })
    }
    
    loadPage()
    

    Also see the attached fiddle for a working example: https://jsfiddle.net/4sza8u2m/