jQuery에게 무언가를 실행하기 전에 모든 이미지가로드 될 때까지 기다리도록 요청하는 공식적인 방법
이렇게하면 jQuery에서 :
$(function() {
alert("DOM is loaded, but images not necessarily all loaded");
});
DOM이로드 될 때까지 기다렸다가 코드를 실행합니다. 모든 이미지가로드되지 않은 경우에도 코드를 실행합니다. 이것은 요소를 표시하거나 숨기거나 이벤트를 첨부하는 것과 같은 DOM 항목을 초기화하는 경우 분명히 원하는 것입니다.
일부 애니메이션을 원하고 모든 이미지가로드 될 때까지 실행되는 것을 원하지 않는다고 가정 해 보겠습니다. jQuery에 공식적인 방법이 있습니까?
내가 가지고있는 가장 좋은 방법은를 사용하는 <body onload="finished()">
것이지만 꼭해야하는 경우가 아니면 그렇게하고 싶지 않습니다.
참고 : Internet Explorer의 jQuery 1.3.1 에는 .NET 내부에서 코드를 실행하기 전에 모든 이미지가로드 될 때까지 실제로 대기 하는 버그가 있습니다 $function() { }
. 따라서 해당 플랫폼을 사용하는 경우 위에서 설명한 올바른 동작 대신 내가 찾고있는 동작을 얻을 수 있습니다.
jQuery를 사용 $(document).ready()
하면 DOM이로 드 $(window).on("load", handler)
될 때 무언가를 실행하고 이미지와 같은 다른 모든 항목도로드 될 때 무언가를 실행합니다.
jollyroger
JPEG 파일 (또는 기타 적절한 파일) 이있는 경우 다음과 같은 완전한 HTML 파일에서 차이점을 확인할 수 있습니다 .
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert ("done");
});
</script>
</head><body>
Hello
<img src="jollyroger00.jpg">
<img src="jollyroger01.jpg">
// : 100 copies of this
<img src="jollyroger99.jpg">
</body>
</html>
이를 통해 DOM이 해당 지점에서 준비되었으므로 이미지가로드되기 전에 경고 상자가 나타납니다. 그런 다음 변경하는 경우 :
$(document).ready(function() {
으로:
$(window).on("load", function() {
다음 경고 상자가 될 때까지 나타나지 않습니다 후 이미지가로드됩니다.
따라서 전체 페이지가 준비 될 때까지 기다리려면 다음과 같이 사용할 수 있습니다.
$(window).on("load", function() {
// weave your magic here.
});
이미지가 요소에로드 될 때 콜백을 실행하거나로드 된 이미지 당 한 번 실행할 수있는 플러그인을 작성했습니다.
$(window).load(function() { .. })
검사 할 선택기를 정의 할 수 있다는 점을 제외하면 과 유사합니다 . #content
(예를 들어)의 모든 이미지 가로드 된 시점 만 알고 싶다면 이것이 바로 플러그인입니다.
또한 CSS에서 참조 이미지 등의 로딩을 지원 background-image
, list-style-image
등
waitForImages jQuery 플러그인
- GitHub 저장소 .
- 읽어보기 .
- 생산 소스 .
- 개발 소스 .
사용 예
$('selector').waitForImages(function() {
alert('All images are loaded.');
});
GitHub 페이지에서 더 많은 문서를 볼 수 있습니다.
$(window).load()
페이지가 처음로드 될 때만 작동합니다. 동적 작업을 수행하는 경우 (예 : 버튼을 클릭하고 새 이미지가로드 될 때까지 기다립니다) 작동하지 않습니다. 이를 위해 내 플러그인을 사용할 수 있습니다.
/**
* Plugin which is applied on a list of img objects and calls
* the specified callback function, only when all of them are loaded (or errored).
* @author: H. Yankov (hristo.yankov at gmail dot com)
* @version: 1.0.0 (Feb/22/2010)
* http://yankov.us
*/
(function($) {
$.fn.batchImageLoad = function(options) {
var images = $(this);
var originalTotalImagesCount = images.size();
var totalImagesCount = originalTotalImagesCount;
var elementsLoaded = 0;
// Init
$.fn.batchImageLoad.defaults = {
loadingCompleteCallback: null,
imageLoadedCallback: null
}
var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
// Start
images.each(function() {
// The image has already been loaded (cached)
if ($(this)[0].complete) {
totalImagesCount--;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image is loading, so attach the listener
} else {
$(this).load(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// An image has been loaded
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
$(this).error(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image has errored
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
}
});
// There are no unloaded images
if (totalImagesCount <= 0)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);
$(window).load
화재 발생 후 요청 된 단일 이미지의 다운로드 완료 알림을 받고 싶은 사람들 은 이미지 요소의 load
이벤트를 사용할 수 있습니다 .
예 :
// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");
// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");
// wait for the image to load
$imgElement.load(function() {
alert("The image has loaded; width: " + $imgElement.width() + "px");
});
지금까지 가장 간단한 해결책을 제시 한 답변은 없습니다.
$('#image_id').load(
function () {
//code here
});
imagesLoaded.js
자바 스크립트 라이브러리를 사용하는 것이 좋습니다 .
왜 jQuery를 사용하지 $(window).load()
않습니까?
https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951에서 ansered
It's a matter of scope. imagesLoaded allows you target a set of images, whereas
$(window).load()
targets all assets — including all images, objects, .js and .css files, and even iframes. Most likely, imagesLoaded will trigger sooner than$(window).load()
because it is targeting a smaller set of assets.
Other good reasons to use imagesloaded
- officially supported by IE8+
- license: MIT License
- dependencies: none
- weight (minified & gzipped) : 7kb minified (light!)
- download builder (helps to cut weight) : no need, already tiny
- on Github : YES
- community & contributors : pretty big, 4000+ members, although only 13 contributors
- history & contributions : stable as relatively old (since 2010) but still active project
Resources
- Project on github: https://github.com/desandro/imagesloaded
- Official website: http://imagesloaded.desandro.com/
- Check if an image is loaded (no errors) in JavaScript
- https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
- imagesloaded javascript library: what is the browser & device support?
With jQuery i come with this...
$(function() {
var $img = $('img'),
totalImg = $img.length;
var waitImgDone = function() {
totalImg--;
if (!totalImg) alert("Images loaded!");
};
$('img').each(function() {
$(this)
.load(waitImgDone)
.error(waitImgDone);
});
});
Demo : http://jsfiddle.net/molokoloco/NWjDb/
Use imagesLoaded PACKAGED v3.1.8 (6.8 Kb when minimized). It is relatively old (since 2010) but still active project.
You can find it on github: https://github.com/desandro/imagesloaded
Their official site: http://imagesloaded.desandro.com/
Why it is better than using:
$(window).load()
Because you may want to load images dynamically, like this: jsfiddle
$('#button').click(function(){
$('#image').attr('src', '...');
});
This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.
var counter = 0;
var size = $('img').length;
$("img").load(function() { // many or just one image(w) inside body or any other container
counter += 1;
counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
this.complete && $(this).load();
});
My solution is similar to molokoloco. Written as jQuery function:
$.fn.waitForImages = function (callback) {
var $img = $('img', this),
totalImg = $img.length;
var waitImgLoad = function () {
totalImg--;
if (!totalImg) {
callback();
}
};
$img.each(function () {
if (this.complete) {
waitImgLoad();
}
})
$img.load(waitImgLoad)
.error(waitImgLoad);
};
example:
<div>
<img src="img1.png"/>
<img src="img2.png"/>
</div>
<script>
$('div').waitForImages(function () {
console.log('img loaded');
});
</script>
'developer tip' 카테고리의 다른 글
C #에서 현재 페이지의 URL을 얻는 방법 (0) | 2020.10.02 |
---|---|
IE에서 개발자 도구를 한 번만 연 후에 만 JavaScript가 작동하는 이유는 무엇입니까? (0) | 2020.10.02 |
jQuery로 요소에 대한 클래스 목록 가져 오기 (0) | 2020.10.02 |
하나를 수정하지 않고 Python에서 두 목록을 연결하는 방법은 무엇입니까? (0) | 2020.10.02 |
메타 데이터 파일 '.dll'을 찾을 수 없습니다. (0) | 2020.10.02 |