3 Ways to Preload Images with CSS, JavaScript, or Ajax---reference

Preloading images is a great way to improve the user experience. When images are preloaded in the browser, the visitor can surf around your site and enjoy extremely faster loading times. This is especially beneficial for photo galleries and other image-heavy sites where you want to deliver the goods as quickly and seamlessly as possible. Preloading images definitely helps users without broadband enjoy a better experience when viewing your content. In this article, we’ll explore three different preloading techniques to enhance the performance and usability of your site.

Method 1: Preloading with CSS and JavaScript

There are many ways to preload images, including methods that rely on CSS, JavaScript, and various combinations thereof. As one of my favorite topics here at Perishable Press, I have covered image preloading numerous times:

Each of these techniques sort of builds on previous methods and remains quite effective and suitable for a variety of design scenarios. Thankfully, readers always seem to chime in on these posts with suggestions and improvements. Recently, Ian Dunn posted an article (404 link removed 2013/08/21) that improves upon my Better Image Preloading without JavaScript method.

With that method, images are easily and effectively preloaded using the following CSS:

#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }

By strategically applying preload IDs to existing (X)HTML elements, we can useCSS’ background property to preload select images off-screen in the background. Then, as long as the paths to these images remains the same when they are referred to elsewhere in the web page, the browser will use the preloaded/cached images when rendering the page. Simple, effective, and noJavaScript required.

As effective as this method is, however, there is room for improvement. As Ian points out, images that are preloaded using this method will be loaded along with the other page contents, thereby increasing overall loading time for the page. To resolve this issue, we can use a little bit of JavaScript to delay the preloading until after the page has finished loading. This is easily accomplished by applying the CSS background properties using Simon Willison’s addLoadEvent() (404 linkremoved 2012/10/18) script:

// better image preloading @ http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/
function preloader() {
	if (document.getElementById) {
		document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";
		document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";
		document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";
	}
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != ‘function‘) {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
addLoadEvent(preloader);

In the first part of this script, we are setting up the actual preloading by targeting specific preload elements with background styles that call the various images. Thus, to use this method, you will need to replace the “preload-01”, “preload-02”, “preload-03”, etc., with the IDs that you will be targeting in your markup. Also, for each of thebackground properties, you will need to replace the “image-01.png”, “image-02.png”, “image-03.png”, etc., with the path and name of your image files. No other editing is required for this technique to work.

Then, in the second part of the script, we are using the addLoadEvent() function to delay execution of our preloader() function until after the page has loaded.

SO what happens when JavaScript is not available on the user’s browser? Quite simply, the images will not be preloaded and will load as normal when called in the web page. This is exactly the sort of unobtrusive, gracefully degrading JavaScript that we really like :)

Method 2: Preloading with JavaScript Only

As effective as the previous method happens to be, I generally find it to be too tedious and time-consuming to actually implement. Instead, I generally prefer to preload images using a straight-up slice of JavaScript. Here are a couple of JavaScript-only preloading methods that work beautifully in virtually every modern browser..

JavaScript Method #1

Unobtrusive, gracefully degrading, and easy to implement, simply edit/add the image paths/names as needed — no other editing required:

<div class="hidden">
	<script type="text/javascript">
		<!--//--><![CDATA[//><!--
			var images = new Array()
			function preload() {
				for (i = 0; i < preload.arguments.length; i++) {
					images[i] = new Image()
					images[i].src = preload.arguments[i]
				}
			}
			preload(
				"http://domain.tld/gallery/image-001.jpg",
				"http://domain.tld/gallery/image-002.jpg",
				"http://domain.tld/gallery/image-003.jpg"
			)
		//--><!]]>
	</script>
</div>

This method is especially convenient for preloading large numbers of images. On one of my gallery sites, I use this technique to preload almost 50 images. By including this script on the login page as well as internal money pages, most of the gallery images are preloaded by the time the user enters their login credentials. Nice.

JavaScript Method #2

Here’s another similar method that uses unobtrusive JavaScript to preload any number of images. Simply include the following script into any of your web pages and edit according to the proceeding instructions:

<div class="hidden">
	<script type="text/javascript">
		<!--//--><![CDATA[//><!--

			if (document.images) {
				img1 = new Image();
				img2 = new Image();
				img3 = new Image();

				img1.src = "http://domain.tld/path/to/image-001.gif";
				img2.src = "http://domain.tld/path/to/image-002.gif";
				img3.src = "http://domain.tld/path/to/image-003.gif";
			}

		//--><!]]>
	</script>
</div>

As you can see, each preloaded image requires a variable definition, “img1 = new Image();”, as well as a source declaration, “img3.src = "../path/to/image-003.gif";”. By replicating the pattern, you can preload as many images as necessary. Hopefully this is clear — if not, please leave a comment and someone will try to help you out.

We can even improve this method a bit by delaying preloading until after the page loads. To do this, we simply wrap the script in a function and useaddLoadEvent() to make it work:

function preloader() {
	if (document.images) {
		var img1 = new Image();
		var img2 = new Image();
		var img3 = new Image();

		img1.src = "http://domain.tld/path/to/image-001.gif";
		img2.src = "http://domain.tld/path/to/image-002.gif";
		img3.src = "http://domain.tld/path/to/image-003.gif";
	}
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != ‘function‘) {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
addLoadEvent(preloader);

Ahhh, the joys of JavaScript!

Method 3: Preloading with Ajax

As if all of that weren’t cool enough, here is a way to preload images using Ajax. This method was discovered at Of Geeks and letters, and uses the DOM to preload not only images, but CSS, JavaScript, and just about anything else. The main benefit of using Ajax over straight JavaScript is that JavaScript and CSSfiles can be preloaded without their contents affecting the current page. For images this is not really an issue, but the method is clean and effective nonetheless.

window.onload = function() {
	setTimeout(function() {
		// XHR to request a JS and a CSS
		var xhr = new XMLHttpRequest();
		xhr.open(‘GET‘, ‘http://domain.tld/preload.js‘);
		xhr.send(‘‘);
		xhr = new XMLHttpRequest();
		xhr.open(‘GET‘, ‘http://domain.tld/preload.css‘);
		xhr.send(‘‘);
		// preload image
		new Image().src = "http://domain.tld/preload.png";
	}, 1000);
};

As is, this code will preload three files: “preload.js”, “preload.css”, and “preload.png”. A timeout of 1000ms is also set to prevent the script from hanging and causing issues with normal page functionality.

To wrap things up, let’s look at how this preloading session would look written in plain JavaScript:

window.onload = function() {

	setTimeout(function() {

		// reference to <head>
		var head = document.getElementsByTagName(‘head‘)[0];

		// a new CSS
		var css = document.createElement(‘link‘);
		css.type = "text/css";
		css.rel  = "stylesheet";
		css.href = "http://domain.tld/preload.css";

		// a new JS
		var js  = document.createElement("script");
		js.type = "text/javascript";
		js.src  = "http://domain.tld/preload.js";

		// preload JS and CSS
		head.appendChild(css);
		head.appendChild(js);

		// preload image
		new Image().src = "http://domain.tld/preload.png";

	}, 1000);

};

Here we are preloading our three files upon page load by creating three elements via the DOM. As mentioned in the original article, this method is inferior to the Ajax method in cases where the preloaded file contents should not be applied to the loading page.

原文地址:http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

3 Ways to Preload Images with CSS, JavaScript, or Ajax---reference

时间: 2024-09-17 01:04:41

3 Ways to Preload Images with CSS, JavaScript, or Ajax---reference的相关文章

利用CSS、JavaScript及Ajax实现图片预加载的三大方法

原文:3 Ways to Preload Images with CSS, JavaScript, or Ajax 译文:利用CSS.JavaScript及Ajax实现图片预加载的三大方法 预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布,也可帮助用户在浏览你网站内容时获得更好的用户体验.本文将分享三个不同的预加载技术,来增强网站的性能与可用性.

[转]利用CSS、JavaScript及Ajax实现图片预加载的三大方法

Perishable Press网站近日发表了一篇文章<3 Ways to Preload Images with CSS, JavaScript, or Ajax>,分享了利用CSS.JavaScript及Ajax实现图片预加载的三大方法.下面为译文. 预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图 片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布,也可帮助用户在浏览你网站内容时获得更好

利用CSS、JavaScript及Ajax实现图片预加载的三大方法及优缺点分析

预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布,也可帮助用户在浏览你网站内容时获得更好的用户体验.本文将分享三个不同的预加载技术,来增强网站的性能与可用性. 方法一:用CSS和JavaScript实现预加载 实现预加载图片有很多方法,包括使用CSS.JavaScript及两者的各种组合.这些技术可根据不同设计场景设计出相应的解决方案,十分高效.

使用CSS、JavaScript及Ajax实现图片预加载的方法详解 

预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布,也可帮助用户在浏览你网站内容时获得更好的用户体验.本文将分享使用CSS.JavaScript及Ajax实现图片预加载的三个不同技术,来增强网站的性能与可用性.一起来看看吧,希望对大家学习web前端有所帮助. 方法一:用CSS和JavaScript实现预加载 实现预加载图片有很多方法,包括使用CSS

网页性能之HTML,CSS,JavaScript

转载自AlloyTeam:http://www.alloyteam.com/2015/05/wang-ye-xing-neng-zhi-html-css-javascript/ 前言 html css javascript可以算是前端必须掌握的东西了,但是我们的浏览器是怎样解析这些东西的呢 我们如何处理html css javascript这些东西来让我们的网页更加合理,在我这里做了一些实验,总结起来给大家看看. 最简单的页面 1 2 3 4 5 6 7 8 9 <!DOCTYPE html>

hta+vbs+js+div+css (javascript是原生态的)

talbe是javascript动态生成的,根据你的sql语句来的,分页是vbs用数组来造的轮子,vbs这脚本虽然强大,却没有返回数据集的东东,数组来做简单的分页还是比较简单的,批量跟新呢?是上传execl来更新的,最好是用vba操作execl的话,直接在execl里修改了立马更新数据库,只是个小工具,目前还不是很强大不是很满意,慢慢做,局限hta不能跨平台只能windows,不能和硬件结合.优点调用webservies不需要考虑域的问题,做一个小巧强悍的工具还是比较方便的,因为hta直接双击就

Brackets - 强大免费的开源跨平台Web前端开发工具IDE (HTML/CSS/Javascript代码编辑器)

Brackets 是一个免费.开源且跨平台的 HTML/CSS/JavaScript 前端 WEB 集成开发环境 (IDE工具).该项目由 Adobe 创建和维护,根据MIT许可证发布,支持 Windows.Linux 以及 OS X 平台. Brackets 的特点是简约.优雅.快捷!它没有很多的视图或者面板,也没太多花哨的功能,它的核心目标是减少在开发过程中那些效率低下的重复性工作,例如浏览器刷新,修改元素的样式,搜索功能等等.和 Sublime Text.Everedit 等通用代码编辑器

分享一个CSS+JavaScript框架materializecss

一.内容: CSS+JavaScript框架materializecss. 二.网址:http://materializecss.com 三.图片:

【JavaScript.6】阶段概念总结之HTML+CSS+JavaScript+xml+xpath+Json+Ajax

[前言] 最近学习了很多BS的新东西,有很多新名称,概念多了,理解也少了,很多东西都混乱.今天静下来把学到的几 个概念性东西总结一下.本文多是一些概念性的个人理解,希望同样存在疑惑的小伙伴看完后能够如入桃源般地豁然 开朗.当然如果我的理解有偏差,请指出来,共同进步. 关于BS的学习,相信很多人都已经走过了,当初最开始接触的是牛腩,里面用到了很多BS的知识,包括HTML. CSS.JavaScript和Ajax等.对于有基础或者正处于迷惑之间的人来说,接下来的话可能会很有感触. [HTML] 首先