图片懒惰加载图片"跳跃"

时间:2016-10-18 06:12:03

标签: javascript html5 image css3 lazyload

嘿,我想懒得加载我页面上的图片,所以我在我的图片标签上创建了一个data-src标签,然后加载它。

我知道有很多图书馆等,但我必须学习js和css所以我厌倦了它,不管任何帮助。

现在的问题是,图像没有初始高度所以当负载时整个页面都是"跳来跳去"

这里是我的js代码:

var smuLazyLoad = (function (self) {
var body = document.getElementsByTagName('body')[0];

var defaultSetup = {
    classSelector: "lazy",
    loadDelay: 100,
    fadeTime: 0.5
};

self.setup = {};

self.init = function (options) {
    options = options || {};
    self.setup.loadDelay = options.loadDelay || defaultSetup.loadDelay;
    self.setup.classSelector = options.classSelector || defaultSetup.classSelector;
    self.setup.fadeTime = options.fadeTime || defaultSetup.fadeTime;
    self.appendHelperStyles();
    self.addEvent('load',window,self.selectImages)
};


self.selectImages = function () {
    var tags = document.getElementsByClassName(self.setup.classSelector);
    for (var i = 0; i < tags.length; i++) {
        self.loadImage(tags[i]);
    }
    self.appendShowCss();
};

self.appendShowCss = function () {
    setTimeout(function () {
        var style = document.createElement('style');
        style.innerText = "." + self.setup.classSelector + "{opacity:1 !important;}";
        body.appendChild(style);
    }, self.setup.loadDelay);
};

self.loadImage = function (tag) {
    var imageUrl = tag.getAttribute('data-src');
    tag.setAttribute('src', imageUrl);
};


self.appendHelperStyles = function () {
    var style = document.createElement('style');
    style.innerText = "." + self.setup.classSelector + "{transition:all ease-in " + self.setup.fadeTime + "s;}";
    body.appendChild(style);
};


self.addEvent = function (ev,ele,func) {
    if (ele.addEventListener)
        ele.addEventListener(ev,func,false);
    else if (elem.attachEvent) {
        ele.attachEvent("on"+ev, func);
    }
    else {
        ele[ev] = func;
    }
};
return self;
 }(smuLazyLoad || {}));

和我的图片标签......(twig / craftcms)

    <img src="/onePxImage.jpg"
         alt="{{ image.title }}"
         data-src="/{{ image.getUrl('teaserImage') }}"
         style="opacity: 0;"
         class="lazy"
         width="{{ image.getHeight('teaserImage') }}"
         height="{{ image.getWidth('teaserImage') }}"
    >

0 个答案:

没有答案