简体   繁体   English

javascript和图像预加载

[英]javascript & image preloading

I need to understand how image preloading works in browsers. 我需要了解图像预加载如何在浏览器中工作。 Lets say I have this piece of code: 可以说我有这段代码:

<script type="text/javascript" language="JavaScript">
    companyLogo = new Image();
    companyLogo.src = "/images/image1.jpg"
</script>

then somewhere below my page i have following. 然后我的页面下面的某个地方,我已经关注。

<img src= "/images/image1.jpg" /> 

now as you can see, first i preloaded the image / images/image1.jpg And then i am using it within my image tag. 现在,您可以看到,首先我预加载了image / images / image1.jpg ,然后在image标签中使用了它。

my website has product images, which are very HD and my entire page sometimes hangs while main image is loading. 我的网站上有非常高清的产品图片,加载主图片时有时整个页面都挂起。 i dont mind size being big for my images, what I want to do is....keep loading the page with content & other elements and show the image as soon as its loaded (however do not HANG/PAUSE the page just because image is not loaded yet). 我不介意图片的尺寸太大,我想做的是....继续在页面上加载内容和其他元素,并在加载后立即显示图片(但是不要因为图像而挂起/暂停页面)尚未加载)。

Now the above approach, what does it exactally do? 现在,上述方法到底能做什么? does it preload the image in cache and waits and hangs the page? 是否将图像预加载到缓存中并等待并挂起页面? or it does exactally what i am trying to do? 还是确实正是我要做什么?

Thanks 谢谢

While it sounds like you should be optimising your images instead, I;m happy to show you how I would do it. 听起来您应该优化图像,但我很高兴向您展示我将如何做。

Don't include the image src, hide it in data. 不包括图像src,将其隐藏在数据中。 (Use correct width and height so your page doesn't jump when they eventually load.) (使用正确的宽度和高度,以便您的页面在最终加载时不会跳动。)

<img src="1px.gif" data-src="http://the.real.src" class="justyouwait" style="width:10000000px; height:1000000px;" />

Then on dom ready, ie when your page has loaded, load them 然后在dom准备就绪时,即在您的页面加载后,加载它们

$(function(){
    $('img.justyouwait').each(function(){
        $(this).attr('src', $(this).data('src'));
    });
});

Or add a bit of niceness 或增加一点美感

$('img.justyouwait').each(function(){
    $(this).css({opacity:0}).load(function(){
        $(this).animate({opacity:1},1000); // fade them in
    }).attr('src', $(this).data('src'));
});

I would do it on DOMReady. 我会在DOMReady上做到这一点。 But it essentially attempts to load the file at the same time the page is loading, there should be no hanging. 但是它实际上是在页面加载的同时尝试加载文件,因此不应挂起。 However it will not "lazy" load the image. 但是,它不会“延迟”加载图像。 Usually this technique is used to load images that MAY be required. 通常,此技术用于加载可能需要的图像。 I would load a low res first, in the HTML, and via javascript update the images once the high res images are ready. 我将首先在HTML中加载低分辨率,一旦高分辨率图像准备就绪,就可以通过javascript更新图像。 Or better yet, simply load a Web safe image and give users a link to the high res if they want it. 或者更好的是,只需加载Web安全图像,并根据需要为用户提供指向高分辨率的链接。

Bad idea to force people to download high-res images. 强迫人们下载高分辨率图像的好主意。 That's a good way to have people avoid your site. 这是让人们避开您的网站的好方法。

EDIT: 编辑:

So you could do something like: 因此,您可以执行以下操作:

<img src="src/to/placeholder.jpg" data-path="path/to/high/res.jpg" class="lazyload"/>

Then have a javascript function do: 然后使用javascript函数执行以下操作:

$('.lazyload').each(function(){
    $(this).attr('src',$(this).data('path'));
});

Not sure if my code is exact, but you get the point. 不知道我的代码是否正确,但是您明白了。

EDIT: When the DOM is loading you are essentially loading the same placeholder image for all of your product images. 编辑:加载DOM时,实际上是为所有产品图像加载相同的占位符图像。 In the background, javascript requests the real image based on the path in data-path. 在后台,javascript根据data-path中的路径请求真实图像。 Then when the image is done loading, the placeholder source gets updated with a nicer image. 然后,当图像加载完成时,占位符源将使用更好的图像进行更新。 Add some fade or whatever if you like. 添加一些淡入淡出或其他(如果您愿意)。

I wrote this simple jQuery plugin to help with this. 我写了这个简单的jQuery插件来解决这个问题。

imgur.js imgur.js

/*
    Plugin: IMGUR
    Author: Drew Dahlman ( www.drewdahlman.com )
    Version: 0.0.2
*/

    (function($) {

        $.fn.imgur = function(options,loaded) {
            var defaults = {
                img: '',
            }

            if(loaded){
                var callback = {
                    loaded: loaded
                }
            }

            return this.each(function() {

                var settings = $.extend(defaults,options);
                var callbacks = $.extend(callback,loaded);
                var _image;

                var $this = $(this);

                function init(){
                    if(callbacks.loaded != null){
                        _image = new Image();
                        _image.onLoad = loaded();
                        _image.src = settings.img;
                    }
                }
                function loaded(){
                    if(callbacks.loaded != null){
                        callbacks.loaded($this,settings.img);
                    }
                }
                init();
        });
        };

    })(jQuery);

How to use 如何使用

in your html assign a class if you have multiple images to load. 在html中分配一个类,如果您要加载多个图像。

<img src='' data-image='images/image1.jpg' class='preload'/>

Then in your javascript call ( this assumes you're using jQuery ) 然后在您的javascript调用中(假设您使用的是jQuery)

<script>
$(".preload").each(function(){
 var $this = $(this);
 $this.imgur({
  img: $this.data('image') // in your case
 },function(el,data){
   el.attr('src',data);
 });
});
</script>

This will use the data-image to load the image then when it's loaded it will add that data to your element that you've supplied it with. 这将使用data-image加载图像,然后在加载图像时将数据添加到您提供的图像元素中。

cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM