>本指南演示瞭如何使用jQuery將圖像預加載到瀏覽器緩存中,從而通過減少加載時間來改善網站性能。 圖像被添加到DOM中的隱藏DIV元素中
(function($,D,W) { var JQUERY4U = {}; JQUERY4U.UTIL = { images: { loadingImage: '<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174076317693190.gif" class="lazy" alt="jquery add image to browser cache " /></img>', ajaxImage: '<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174076317789628.gif" class="lazy" alt="jquery add image to browser cache " /></img>', savingImage: '<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174076317761887.gif" class="lazy" alt="jquery add image to browser cache " /></img>' }, preloadImages: function() { $('body').append('<div id="img-cache" style="display:none"></div>'); $.each(JQUERY4U.UTIL.images, function(i,v) { $('#img-cache').append(v); }); } } $(D).ready(function($) { JQUERY4U.UTIL.preloadImages(); }); })(jQuery,document,window);
,並將圖像元素附加到其上。 div
循環通過$.each
>對象迭代,將每個圖像添加到緩存。 images
替代方法:
>一種更簡單的方法,用於預加載圖像,而沒有隱藏的div:此方法直接創建
// Array of image URLs var imageArray = ['image1.jpeg', 'image2.png', 'image3.gif']; // Preload images $.each(imageArray, function(index, src) { new Image().src = src; });
Image
>常見問題src
本節回答有關使用jQuery向網頁添加圖像的常見問題。
添加圖像
使用
>使用JavaScript append()
$('#myDiv').append('<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174076317883720.png" class="lazy" alt="jquery add image to browser cache " />');
和
createElement()
>用jQuery的appendChild()
var img = document.createElement('img'); img.src = 'image.png'; document.getElementById('myDiv').appendChild(img);
動態附加圖像
append()
var imagePath = 'image.png'; var altText = 'My Image'; $('#myDiv').append('<img src="' + imagePath + '" alt="' + altText + '">');
將圖像附加圖像
通過laravel中的ajax附加圖像
$.ajax({ url: '/get-image-path', // Endpoint to fetch image path success: function(data) { $('#myDiv').append('<img src="' + data.imagePath + '" id="dynamicImg' + data.imageId + '" alt="Dynamic Image">'); } });
助手
以上是jQuery將圖像添加到瀏覽器緩存的詳細內容。更多資訊請關注PHP中文網其他相關文章!