首页 > 解决方案 > Sweetalert2 模态在图像出现在模态之前短暂加载

问题描述

我正在使用 Sweetalert2 来显示一个内部有图像的模式。虽然它工作正常,但没有图像的模态会在图像出现之前显示一瞬间。我怎样才能等到图像完全加载。这是我尝试过但不起作用的方法:(加载页面时调用 loadPage 。)

    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({

    })
}

标签: javascriptsweetalert2

解决方案


你这样做的方式应该没有任何闪烁。图像被下载、缓存并且在随后的请求中它应该从缓存中提供。我创建了一个小提琴,无法重建您描述的问题。

尽管我创建了另一种方法,将下载的图像保存为 dataURI 并将其传递给您的 SweetAlert 实例。这样,您可以防止多次意外下载图像。

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()

另请参阅随附的小提琴以获取工作示例:https ://jsfiddle.net/4sza8u2m/


推荐阅读