program story

이미지가로드 된시기를 감지하는 브라우저 독립적 인 방법

inputbox 2020. 12. 31. 08:14
반응형

이미지가로드 된시기를 감지하는 브라우저 독립적 인 방법


IE에서는 onreadystatechange가 가능합니다. 온로드가 있지만 무서운 것을 읽었습니다 . jQuery는 DOM의로드 이벤트를 "ready"로 아주 멋지게 래핑합니다. 다른 멋진 라이브러리의 이미지 로딩 구현에 대해 무지한 것 같습니다.

컨텍스트는 다운로드에 시간이 걸릴 수있는 이미지를 동적으로 (서버 콜백을 통해) 생성하고 있다는 것입니다. IE 전용 코드에서 img 요소의 src를 설정 한 다음 onreadystatechange 이벤트가 "complete"상태로 실행되면 DOM에 추가하여 사용자가 볼 수 있도록합니다.

"네이티브"자바 스크립트 솔루션이나 작업을 수행하는 라이브러리에 대한 포인터에 만족합니다. 거기에는 너무 많은 도서관이 있으며 이것이 올바른 것에 대해 알지 못하는 경우라고 확신합니다. 즉, 우리는 이미 jQuery 사용자이므로이 기능을 얻기 위해 매우 큰 라이브러리를 추가하고 싶지는 않습니다.


참고 : 필자는 2010 년에이 글을 썼는데, 브라우저는 IE 8/9 베타, Firefox 3.x, Chrome 4.x였습니다. 연구 목적으로 만 사용하십시오. 최신 브라우저에 복사 / 붙여 넣기하여 문제없이 작동 할 수 있을지 의심됩니다.

경고 : 2017 년이되었습니다. 지금도 여전히이 점에 대해 점수를 얻습니다. 연구 목적으로 만 사용하십시오. 나는 현재 이미지 로딩 상태를 감지하는 방법을 모르지만, 아마도 이것보다 훨씬 더 우아한 방법이있을 것입니다. 적어도 나는 진지하게 거기에 있기를 바랍니다. 더 많은 연구없이 프로덕션 환경에서 내 코드를 사용하지 않는 것이 좋습니다.

경고 2 부 Electric Boogaloo : 이제 2019 년이되었습니다. 이제 대부분의 jQuery 기능이 vanilla JS에 내장되어 있습니다. 아직 사용 중이라면 MDN으로 가서 바닐라 JS가 제공하는 새롭고 재미있는 것들을 읽어 볼 시간 입니다.


이 파티에 조금 늦었습니다.이 답변이 다른 사람에게 도움이 될 것입니다 ...

jQuery를 사용하는 경우 주식 이벤트 핸들러 (onclick / onmouseover / etc)를 사용하지 않고 실제로 사용을 중지하십시오. API 에서 제공 한 이벤트 메서드를 사용합니다 .


이미지가 메모리에로드 될 때로드 이벤트가 트리거되기 때문에 이미지가 본문에 추가되기 전에 경고합니다. 그것은 당신이 말한대로 정확히 수행하고 있습니다 : test.jpg 가로 드 될 때 test.jpg의 src로 이미지를 만든 다음 본문에 추가하십시오.

var img = $('<img src="test.jpg" />');
img.load(function() {
    alert('Image Loaded');
});
$('body').append(img);

이렇게하면 이미지가 본문에 삽입 된 후 다시 한 번 다음과 같이 경고합니다. 이미지 생성, 이벤트 설정 (src가 설정되지 않았으므로로드되지 않음), 이미지를 본문에 추가 (여전히 src 없음), 이제 src를 설정합니다. 이제 이미지가로드되어 이벤트가 트리거됩니다.

var img = $('<img />');
img.load(function() {
    alert('Image Loaded');
});
$('body').append(img);
$img.attr('src','test.jpg');

물론 오류 처리기를 추가하고 bind ()를 사용하여 여러 이벤트를 병합 할 수도 있습니다.

var img = $('<img />');
img.bind({
    load: function() {
        alert('Image loaded.');
    },
    error: function() {
        alert('Error thrown, image didn\'t load, probably a 404.');
    }
});
$('body').append(img);
img.attr('src','test.jpg');

@ChrisKempen의 요청에 따라 ...

다음은 DOM이로드 된 후 이미지가 손상되었는지 확인하는 비 이벤트 기반 방법입니다. 이 코드는 이미지가 존재하는지 확인하기 위해 naturalWidth, naturalHeight 및 complete 속성을 사용 하는 StereoChrome 기사에서 파생 된 코드입니다 .

$('img').each(function() {
    if (this.naturalWidth === 0 || this.naturalHeight === 0 || this.complete === false) {
        alert('broken image');
    }
});

W3C의 사양에 따르면 , 오직 몸과 FRAMESET 요소에 부착 할 수있는 "온로드"이벤트를 제공합니다. 일부 브라우저는 상관없이 지원하지만 W3C 사양을 구현할 필요가 없다는 점을 유의하십시오.

이 토론과 관련이있을 수 있지만 반드시 필요한 답변은 아니지만이 토론은 다음과 같습니다.

이미지가 캐시에있을 때 Internet Explorer에서 Image.onload 이벤트가 발생하지 않습니다.


필요 와 관련있을 수있는 다른 것은 동적으로로드 된 DOM 요소에 대해 합성 된 "onload"이벤트를 지원하는 정보입니다 .

동적으로 생성 된 DOM 요소가 DOM에 추가되었는지 어떻게 확인할 수 있습니까?


내가 찾은 유일한 신뢰할 수있는 방법은 다음과 같이 클라이언트 측에서 모든 작업을 수행하는 것입니다.

var img = new Image();
img.onload = function() {
  alert('Done!');
}
img.src = '/images/myImage.jpg';

onload잘 작동해야 한다고 생각 합니다. 이미지에 대한 마크 업을 생성해야합니까, 아니면 정적으로 추가 할 수 있습니까? 후자의 경우 다음을 제안합니다.

<img src="foo.png" class="classNeededToHideImage" onload="makeVisible(this)">

또는를 사용 window.onload하여 모든 이미지를 한 번에 표시 할 수 있습니다. window.onload모든 외부 리소스가로드 된 후 실행됩니다.

If you want to add the images dynamically, you first have to wait for the DOM to be ready to be modified, ie use jQuery or implement your own DOMContentLoaded hack for browsers which don't support it natively.

Then, you create your image objects, assign onload listeners to make them visible and/or add them to the document.

Even better (but slightly more complicated) would be to create and start loading the images immediately when the script executes. On DOMContentLoaded, you'll have to check each image for complete to decide whether to add them immediately to the document or wait for the image's onload listener to fire.


Okay, I'll try to summarize the various partial answers here (including mine).

It would appear the answer is to use onload, which is "widely supported" though not officially required according to standards. Note that for IE in particular, you must set onLoad before setting the src attribute or it may not fire onload when loading an image from the cache. This seems like best practice in any case: set up your event handlers before you start firing events. Where onload is not supported, one should assume that the functionality simply isn't available.


It would appear the answer is use onreadystatechange in IE, and onLoad in other browsers. If neither one is available, do something else. onLoad would be preferable, but IE doesn't fire it when loading an image from the cache, as noted in one of the answers below.


If im not mistaken in javascript an image tag has the events onload and onerror

here is an intersting bit of code i did to hide broken images

in a style tag

img.failed{
   display:none;
}

using the img onerror i had a piece of javascript that did this.className=failed and it would hide the image if it errored

however i may have misunderstood what your goal


HTML

<img id="myimage" src="http://farm4.static.flickr.com/3106/2819995451_23db3f25fe_t.jpg"/>​

SCRIPT

setTimeout(function(){
    $('#myimage').attr('src','http://cdn.redmondpie.com/wp-content/uploads/2011/05/canarylogo.png').load(function(){
        alert('Main Image Loaded');

        $('#myimage').attr('src','image.jpg').bind({
            load: function(){
                alert('Image loaded.');
            },
            error: function(){
                alert('Image not loaded.');
            }
        });
    });
},1000);

JS Fiddle

http://jsfiddle.net/gerst20051/sLge3/


Using a data URI is the way to go. However, using an SVG instead of a GIF provides more flexibility. You can quickly change the size. Just run this in a JavaScript console:

var width = 1;
var height = 1;
'data:image/svg+xml;base64,' +
btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);

Example output:

data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxIiBoZWlnaHQ9IjEiLz4=

I threw together a quick CodePen utility to create transparent SVGs with arbitrary dimensions. It's pretty basic, so you'll need to modify it if you want to add color or other features to the image.

The biggest advantage over a single-pixel image is that it allows aspect ratio to be preserved. This is important for dynamically-sized images, as layout is often performed before the src changes to a real image (if that's the intended purpose). Until the src changes, image will be square, which may be undesirable.

ReferenceURL : https://stackoverflow.com/questions/821516/browser-independent-way-to-detect-when-image-has-been-loaded

반응형