Preloading images with JavaScript

后端 未结 14 1225
太阳男子
太阳男子 2020-11-22 03:17

Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
{
    var img=new Image(         


        
14条回答
  •  迷失自我
    2020-11-22 03:42

    I recommend you use a try/catch to prevent some possible issues:

    OOP:

        var preloadImage = function (url) {
            try {
                var _img = new Image();
                _img.src = url;
            } catch (e) { }
        }
    

    Standard:

        function preloadImage (url) {
            try {
                var _img = new Image();
                _img.src = url;
            } catch (e) { }
        }
    

    Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.

提交回复
热议问题