Most images on the web are superfluous. If I might be a jerk for a bit, 99% of them aren’t even that helpful at all (although there are rare exceptions). That’s because images don’t often complement the text they’re supposed to support and instead hurt users, taking forever to load and blowing up data caps like some sort of performance tax.
Thankfully, this is mostly a design problem today because making images performant and more user-friendly is so much easier than it once was. We have better image formats likeWebP(and soon, perhaps,JPEG XL). We have the magic ofresponsive imagesof course. And there are tons of great tools out there, like ImageOptim, as well as resources such as Addy Osmani’s new book.
Although perhaps my favorite way to improve image performance is withlazy loading:
<img src="/static/imghwm/default1.png" data-src="image.jpg" class="lazy" href="image.webp" alt="Image description" loading="lazy">
This image will only load when a user scrolls down the page so it’s visible to the user — which removes it from the initial page load and that’s just great! Making that initial load of a webpage lightningfast is a big deal.
But maybe there are images that should never load at all. Perhaps there are situations where it’d be better if a person could opt-into seeing it. Here’s one example: take the text-only version ofNPRand click around for a bit. Isn’t it… just so great?! It’s readable! There’s no junk all over the place, it respects me as a user and — sweet heavens — is itfast.
So! What if we could show images on a website but only once they are clicked or tapped? Wouldn’t it be neat if we could show a placeholder and swap it out for the real image on click? Something like this:
Well, I had two thoughts here as to how to build this chap (the golden rule is that there’s never one way to build anything on the web).
Method #1: Using
without a src attribute
We can remove the src attribute of an tag to hide an image. We could then put the image file in an attribute, like data-src or something, just like this:
<img src="/static/imghwm/default1.png" data-src="image.jpg" class="lazy" data- alt="Photograph of hot air balloons by Musab Al Rawahi. 144kb">
By default, most browsers will show a broken image icon that you’re probably familiar with:
Okay, so it’s sort of accessible. I guess? You can see the alt tag rendered on screen automatically, but with a light dash of JavaScript, we can then swap out the src with that attribute:
document.querySelectorAll("img").forEach((item) => { item.addEventListener("click", (event) => { const image = event.target.getAttribute("data-src"); event.target.setAttribute("src", image); }); });
Now we can add some styles and ugh, oh no:
Ugh. In some browsers there’ll be a tiny broken image icon in the bottom when the image hasn’t loaded. The problem here is that browsers don’t give you a way to remove the broken image icon with CSS (and we probably shouldn’t be allowed to anyway). It’s a bit annoying to style the alt text, too. But if we remove the alt attribute altogether, then the broken image icon is gone, although this makes the unusable without JavaScript. So removing that alt text is a no-go.
As I said: Ugh. I don’t think there’s a way to make this method work (although please prove me wrong!).
Method #2: Using links to create an image
The other option we have is to start with the humble hyperlink, like this:
<a href="image.jpg">Photograph of hot air balloons by Musab Al Rawahi. 144kb</a><a></a>
Which, yep, nothing smart happening yet — this will just render a link to an image:
That works accessibility-wise, right? If we don’t have any JavaScript, then all we have is just a link that folks can optionally click. Performance-wise, it can’t get much faster than plain text!
But from here, we can reach for JavaScript to stop the link from loading on click, grab the href attribute within that link, create an image element and, finally, throw that image on the page and remove the old link once we’re done:
document.querySelectorAll(".load-image").forEach((item) => { item.addEventListener("click", (event) => { const href = event.target.getAttribute("href"); const newImage = document.createElement("img"); event.preventDefault(); newImage.setAttribute("src", href); document.body.insertBefore(newImage, event.target); event.target.remove(); }); });
We could probably style this placeholder link to make it look a bit nicer than what I have below. But this is just an example. Go ahead and click the link to load the image again:
And there you have it! It isn’t groundbreaking or anything, and I’m sure someone’s done this before at some point or another. But if we wanted to be extremely radical about performance beyond the first paint and initial load, then I think this is an okay-ish solution. If we’re making a text-only website then I think this is definitely the way to go.
Perhaps we could also make a web component out of this, or even detect if someone hasprefers-reduced-dataand then only load images if someone has enough data or something. What do you think?
위 내용은 클릭에 이미지를 표시하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

앵커 포지셔닝이 HTML 소스 순서를 철회한다는 사실은 컨텐츠와 프리젠 테이션 사이의 또 다른 문제가있는 또 다른 분리 때문에 CSS-Y이기 때문입니다.

기사는 CSS 마진 속성, 특히 "마진 : 40px 100px 120px 80px", 응용 프로그램 및 웹 페이지 레이아웃에 미치는 영향에 대해 설명합니다.

이 기사에서는 CSS 국경 속성에 대해 설명하고 사용자 정의, 모범 사례 및 응답성에 중점을 둡니다. 주요 인수 : Border-Radius는 반응 형 디자인에 가장 효과적입니다.

이 기사에서는 CSS 배경 속성, 웹 사이트 디자인 향상에 대한 사용 및 피하는 일반적인 실수에 대해 설명합니다. 주요 초점은 배경 크기를 사용한 반응 형 디자인에 중점을 둡니다.

기사는 CSS HSL 색상, 웹 디자인에서의 사용 및 RGB의 장점에 대해 설명합니다. 주요 초점은 직관적 인 색상 조작을 통해 설계 및 접근성을 향상시키는 데 있습니다.

이 기사는 CSS의 주석 사용에 대해 논의하고 단일 라인 및 멀티 라인 주석 구문을 자세히 설명합니다. 의견은 코드 가독성, 유지 관리 및 협업을 향상 시키지만 제대로 관리하지 않으면 웹 사이트 성능에 영향을 줄 수 있다고 주장합니다.

이 기사는 CSS 선택기, 유형 및 HTML 요소 스타일링을위한 사용법에 대해 설명합니다. ID와 클래스 선택기를 비교하고 복잡한 선택기의 성능 문제를 해결합니다.

이 기사는 CSS 우선 순위에 대해 논의하며, 가장 높은 특이성을 가진 인라인 스타일에 중점을 둡니다. CSS 충돌 관리를위한 특이성 수준, 재정의 방법 및 디버깅 도구를 설명합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

드림위버 CS6
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

WebStorm Mac 버전
유용한 JavaScript 개발 도구
