CSS 이미지 미리로드
버튼을 클릭하여 배포되는 숨겨진 연락처 양식이 있습니다. 해당 필드는 CSS 배경 이미지로 설정되며 항상 토글 된 div보다 약간 늦게 나타납니다.
<head>
섹션 에서이 스 니펫을 사용 했지만 운이 없었습니다 (캐시를 지운 후).
<script>
$(document).ready(function() {
pic = new Image();
pic2 = new Image();
pic3 = new Image();
pic.src="<?php bloginfo('template_directory'); ?>/images/inputs/input1.png";
pic2.src="<?php bloginfo('template_directory'); ?>/images/inputs/input2.png";
pic3.src="<?php bloginfo('template_directory'); ?>/images/inputs/input3.png";
});
</script>
나는 jQuery를 내 라이브러리로 사용하고 있으며,이 문제를 정리하는데도 사용할 수 있다면 멋질 것입니다.
당신의 생각에 감사드립니다.
CSS 만 사용하여 이미지 미리로드
아래 코드 body
에서는 페이지에 존재하는 유일한 요소 중 하나이기 때문에 요소를 무작위로 선택하고 있습니다.
"트릭"이 작동하려면 여러 URL을로드 content
할 수 있도록 편안하게 설정 하는 속성을 사용해야합니다 . 그러나 표시된 것처럼 가상 요소는 숨겨진 상태로 유지 되므로 이미지가 렌더링되지 않습니다.::after
body::after{
position:absolute; width:0; height:0; overflow:hidden; z-index:-1; // hide images
content:url(img1.png) url(img2.png) url(img3.gif) url(img4.jpg); // load images
}
데모
스프라이트 이미지 를 사용하여 http 요청을 줄이고 (상대적으로 작은 크기의 이미지가 많은 경우) HTTP2 가 사용 되는 위치에서 이미지가 호스팅되는지 확인하는 것이 좋습니다 .
원래 코드가 작동하는지 확인할 수 있습니다. 나는 우연히 잘못된 길을 가진 이미지를 고수하고 있었다.
다음은 테스트입니다. http://paragraphe.org/slidetoggletest/test.html
<script>
var pic = new Image();
var pic2 = new Image();
var pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>
HTML <link> 태그를 사용하여 이미지 미리로드
이 질문의 방문자 대부분이 "페이지 렌더링이 시작되기 전에 이미지를 미리로드하려면 어떻게해야합니까?"라는 대답을 찾고 있다고 생각 합니다. 이 문제에 대한 최선의 해결책은 <link>
태그를 사용하는 것입니다. 태그 <link>
는 페이지의 추가 렌더링을 차단할 수 있기 때문 입니다. 선점 형 보기
rel
( 현재 문서와 링크 된 문서 간의 관계 ) 속성 의 다음 두 가지 값 옵션은 문제와 가장 관련이 있습니다.
- prefetch : 페이지를 렌더링하는 동안 주어진 리소스를로드합니다.
- preload : 페이지 렌더링이 시작되기 전에 주어진 리소스를로드합니다.
따라서 태그 의 렌더링 프로세스가 시작 되기 전에 리소스 ( 이 경우 이미지 ) 를로드 <body>
하려면 다음을 사용하세요.
<link rel="preload" as="image" href="IMAGE_URL">
<body>
렌더링 하는 동안 리소스를로드하고 싶지만 나중에 동적으로 사용할 계획이고 로딩 시간으로 사용자를 괴롭 히고 싶지 않은 경우 다음을 사용합니다.
<link rel="prefetch" href="RESOURCE_URL">
http://css-tricks.com/snippets/css/css-only-image-preloading/
기법 # 1
요소의 일반 상태에 이미지를로드하고 배경 위치로만 이동합니다. 그런 다음 배경 위치를 이동하여 마우스 오버시 표시합니다.
#grass { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background-position: bottom left; }
기법 # 2
문제의 요소에 이미 적용된 배경 이미지가 있고 해당 이미지를 변경해야하는 경우 위의 방법이 작동하지 않습니다. 일반적으로 여기서 스프라이트 (결합 된 배경 이미지)로 이동하고 배경 위치를 이동합니다. 그러나 그것이 가능하지 않다면 이것을 시도하십시오. 이미 사용 중이지만 배경 이미지가없는 다른 페이지 요소에 배경 이미지를 적용하십시오.
#random-unsuspecting-element { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background: url(images/grass.png) no-repeat; }
이것을 시도하십시오 :
var c=new Image("Path to the background image");
c.onload=function(){
//render the form
}
With this code you preload the background image and render the form when it's loaded
For preloading background images set with CSS, the most efficient answer i came up with was a modified version of some code I found that did not work:
$(':hidden').each(function() {
var backgroundImage = $(this).css("background-image");
if (backgroundImage != 'none') {
tempImage = new Image();
tempImage.src = backgroundImage;
}
});
The massive benefit of this is that you don't need to update it when you bring in new background images in the future, it will find the new ones and preload them!
If you're reusing these bg images anywhere else on your site for form inputs, you probably want to use an image sprite. That way you can centrally manage your images (instead of having pic1, pic2, pic3, etc...).
Sprites are generally faster for the client, since they are only requesting one (albeit slightly larger) file from the server instead of multiple files. See SO article for more benefits:
Then again, this might not be helpful at all if you're just using these for one form and you really only want to load them if the user requests the contact form...might make sense though.
http://www.alistapart.com/articles/sprites
how about loading that background image somewhere hidden. That way it will be loaded when the page is opened and wont take any time once the form is created using ajax:
body {
background: #ffffff url('img_tree.png') no-repeat -100px -100px;
}
You could use this jQuery plugin waitForImage or you could put you images into an hidden div or (width:0 and height:0) and use onload event on images.
If you only have like 2-3 images you can bind events and trigger them in a chain so after every image you can do some code.
The only way is to Base64 encode the image and place it inside the HTML code so that it doesn't need to contact the server to download the image.
This will encode an image from url so you can copy the image file code and insert it in your page like so...
body {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}
When there is no way to modify CSS code and preload images with CSS rules for :before
or :after
pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body
tag or just after stylesheets.
getUrls() {
const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;
let urls = [];
for (let i = 0; i < document.styleSheets.length; i++) {
let cssRules = document.styleSheets[i].cssRules;
for (let j = 0; j < cssRules.length; j++) {
let cssRule = cssRules[j];
if (!cssRule.selectorText) {
continue;
}
for (let k = 0; k < cssRule.style.length; k++) {
let property = cssRule.style[k],
urlMatch = cssRule.style[property].match(urlRegExp);
if (urlMatch !== null) {
urls.push(urlMatch[2]);
}
}
}
}
return urls;
}
preloadImages() {
return new Promise(resolve => {
let urls = getUrls(),
loadedCount = 0;
const onImageLoad = () => {
loadedCount++;
if (urls.length === loadedCount) {
resolve();
}
};
for (var i = 0; i < urls.length; i++) {
let image = new Image();
image.src = urls[i];
image.onload = onImageLoad;
}
});
}
document.addEventListener('DOMContentLoaded', () => {
preloadImages().then(() => {
// CSS images are loaded here
});
});
If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)
참고URL : https://stackoverflow.com/questions/1373142/preloading-css-images
'Programming' 카테고리의 다른 글
Android Studio Checkout Github 오류“CreateProcess = 2”(Windows) (0) | 2020.08.10 |
---|---|
앱이 설정되지 않음 :이 앱은 아직 개발 모드입니다. (0) | 2020.08.10 |
정의되지 않은 메서드 mysqli_stmt :: get_result 호출 (0) | 2020.08.10 |
전체 라인을 sed로 바꾸는 방법? (0) | 2020.08.10 |
디렉토리에 파일이 포함되어 있는지 쉘 스크립트에서 확인 (0) | 2020.08.10 |