jQuery로 이미지 미리로드
JavaScript로 이미지를 미리로드하는 빠르고 쉬운 방법을 찾고 있습니다. 중요한 경우 jQuery를 사용하고 있습니다.
나는 여기에서 이것을 보았다 ( http : //nettuts.com ... ) :
function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
그러나 내가 원하는 것에 대해 약간 과도하게 보입니다!
이 작업을 수행하는 jQuery 플러그인이 있다는 것을 알고 있지만 모두 크기가 약간 커 보입니다. 이미지를 빠르고 쉽고 빠르게 미리로드하는 방법이 필요합니다!
빠른 및 쉬운 :
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
또는 jQuery 플러그인이 필요한 경우 :
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
다음은 실제로 이미지를 DOM에로드하고 기본적으로 숨기는 첫 번째 응답의 수정 된 버전입니다.
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
이 함수를 사용하면 모든 사진을로드 할 때 콜백을 트리거 할 수 있습니다. 그러나 하나 이상의 리소스가로드되지 않은 경우 콜백을 트리거하지 않습니다. 이는 onerror
콜백 을 구현 하고 loaded
값을 증가 시키거나 오류를 처리하여 쉽게 수정할 수 있습니다 .
var preloadPictures = function(pictureUrls, callback) {
var i,
j,
loaded = 0;
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback();
}
};
// Use the following callback methods to debug
// in case of an unexpected behavior.
img.onerror = function () {};
img.onabort = function () {};
img.src = src;
} (new Image(), pictureUrls[i]));
}
};
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('a');
});
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('b');
});
JP, 솔루션을 확인한 후에도 Firefox에서 페이지로드와 함께 이동하기 전에 이미지를 미리로드하지 않는 문제가 여전히 발생했습니다. sleep(5)
내 서버 측 스크립트 에 일부 를 넣어 이것을 발견했습니다 . 나는 이것을 해결하는 것처럼 보이는 당신을 기반으로 다음 솔루션을 구현했습니다.
기본적으로 모든 이미지가 제대로로드 된 후 호출되도록 jQuery 사전로드 플러그인에 콜백을 추가했습니다.
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
내 맥락에서 흥미롭게 다음과 같이 사용하고 있습니다.
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
바라건대 이것은 Google에서이 페이지를 방문한 사람이 Ajax 호출에서 이미지를 미리로드하는 솔루션을 찾는 데 도움이되기를 바랍니다.
이 한 줄의 jQuery 코드는 DOM 요소 img를 표시하지 않고 생성 (및로드)합니다.
$('<img src="img/1.jpg"/>');
$.fn.preload = function (callback) {
var length = this.length;
var iterator = 0;
return this.each(function () {
var self = this;
var tmp = new Image();
if (callback) tmp.onload = function () {
callback.call(self, 100 * ++iterator / length, iterator === length);
};
tmp.src = this.src;
});
};
사용법은 매우 간단합니다.
$('img').preload(function(perc, done) {
console.log(this, perc, done);
});
http://jsfiddle.net/yckart/ACbTK/
나는 이것을 처리하는 작은 플러그인이 있습니다.
waitForImages 라고 img
하며 CSS의 이미지에 대한 참조가있는 요소 또는 모든 요소를 처리 할 수 있습니다 ( 예 : div { background: url(img.png) }
.
CSS에서 참조 된 이미지를 포함하여 모든 이미지 를로드 하려면 다음과 같이하십시오. :)
$('body').waitForImages({
waitForAll: true,
finished: function() {
// All images have loaded.
}
});
CSS display:none;
규칙을 사용하여 HTML 어딘가에 이미지를로드 한 다음 js 또는 jquery로 원할 때 표시 할 수 있습니다.
don't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed
example: Html
<img src="someimg.png" class="hide" alt=""/>
Css:
.hide{
display:none;
}
jQuery:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!
this jquery imageLoader plugin is just 1.39kb
usage:
$({}).imageLoader({
images: [src1,src2,src3...],
allcomplete:function(e,ui){
//images are ready here
//your code - site.fadeIn() or something like that
}
});
there are also other options like whether you want to load the images synchronously or asychronously and a complete event for each individual image.
A quick, plugin-free way to preload images in jQuery and get a callback function is to create multiple img
tags at once and count the responses, e.g.
function preload(files, cb) {
var len = files.length;
$(files.map(function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
preload(["one.jpg", "two.png", "three.png"], function() {
/* Code here is called once all files are loaded. */
});
Note that if you want to support IE7, you'll need to use this slightly less pretty version (Which also works in other browsers):
function preload(files, cb) {
var len = files.length;
$($.map(files, function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
Thanks for this! I'd liek to add a little riff on the J-P's answer - I don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly. This is handy because I have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.
$("img").each(function(){
var imgsrc = $(this).attr('src');
if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
imgsrc = thumbToLarge(imgsrc);
(new Image()).src = imgsrc;
}
});
Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.
In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. The thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.
Hope this helps someone.
jQuery.preloadImage=function(src,onSuccess,onError)
{
var img = new Image()
img.src=src;
var error=false;
img.onerror=function(){
error=true;
if(onError)onError.call(img);
}
if(error==false)
setTimeout(function(){
if(img.height>0&&img.width>0){
if(onSuccess)onSuccess.call(img);
return img;
} else {
setTimeout(arguments.callee,5);
}
},0);
return img;
}
jQuery.preloadImages=function(arrayOfImages){
jQuery.each(arrayOfImages,function(){
jQuery.preloadImage(this);
})
}
// example
jQuery.preloadImage(
'img/someimage.jpg',
function(){
/*complete
this.width!=0 == true
*/
},
function(){
/*error*/
}
)
I use the following code:
$("#myImage").attr("src","img/spinner.gif");
var img = new Image();
$(img).load(function() {
$("#myImage").attr("src",img.src);
});
img.src = "http://example.com/imageToPreload.jpg";
I would use an Manifest file to tell (modern) web browsers to also load all relevant images and cache them. Use Grunt and grunt-manifest to do this automatically and never worry again about preload scripts, cache invalidators, CDN etc.
https://github.com/gunta/grunt-manifest
This works for me even in IE9:
$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });
I wanted to do this with a Google Maps API custom overlay. Their sample code simply uses JS to insert IMG elements and the image placeholder box is displayed until the image is loaded. I found an answer here that worked for me : https://stackoverflow.com/a/10863680/2095698 .
$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
This preloads an image as suggested before, and then uses the handler to append the img object after the img URL is loaded. jQuery's documentation warns that cached images don't work well with this eventing/handler code, but it's working for me in FireFox and Chrome, and I don't have to worry about IE.
function preload(imgs) {
$(imgs).each(function(index, value) {
$('<img />').attr('src', value).appendTo('body').css('display', 'none');
});
}
.attr('src',value)
not .attr('src',this)
just to point it out :)
5 lines in coffeescript
array = ['/img/movie1.png','/img/movie2.png','/img/movie3.png']
$(document).ready ->
for index, image of array
img[index] = new Image()
img[index].src = image
For those who know a little bit of actionscript, you can check for flash player, with minimal effort, and make a flash preloader, that you can also export to html5/Javascript/Jquery. To use if the flash player is not detected, check examples on how to do this with the youtube role back to html5 player:) And create your own. I do not have the details, becouse i have not started yet, if i dont forgot, i wil post it later and will try out some standerd Jquery code to mine.
참고URL : https://stackoverflow.com/questions/476679/preloading-images-with-jquery
'developer tip' 카테고리의 다른 글
오래되고 사용되지 않는 Docker 이미지를 제거하는 방법 (0) | 2020.09.30 |
---|---|
강제로 "git push"로 원격 파일 덮어 쓰기 (0) | 2020.09.30 |
변수 유형이 문자열인지 확인하는 방법은 무엇입니까? (0) | 2020.09.30 |
CSS 폭발 관리 (0) | 2020.09.30 |
HTML Canvas를 gif / jpg / png / pdf로 캡처 하시겠습니까? (0) | 2020.09.30 |