Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在HTML中的两个img元素之间共享一个物理图像_Javascript_Jquery_Html - Fatal编程技术网

Javascript 在HTML中的两个img元素之间共享一个物理图像

Javascript 在HTML中的两个img元素之间共享一个物理图像,javascript,jquery,html,Javascript,Jquery,Html,有一个image元素,我如何使用这个img元素而不向服务器发送另一个请求。需要注意的是,我不希望image1.jpg从Web服务器下载两次。有什么想法吗 function loadCarousels(carouselLoc, carouselId) { $("li").find(carouselLoc).each(function (index) { var img = this; var outer = 0; $(carous

有一个image元素,我如何使用这个img元素而不向服务器发送另一个请求。需要注意的是,我不希望image1.jpg从Web服务器下载两次。有什么想法吗

    function loadCarousels(carouselLoc, carouselId) {

    $("li").find(carouselLoc).each(function (index) {
        var img = this;
        var outer = 0;

        $(carouselId).find("ul").each(function (innerIndex) {
            var liX = document.createElement("li");
            $(this).append(liX);
            var imgInner = document.createElement("img");
            imgInner.src = img.src;
            $(imgInner).appendTo(liX);
            console.log($(this));
        });
    });
}

这是我目前尝试的方式,但它不起作用。它会创建一个单独的图像。

浏览器应该已经非常积极地缓存图像:Chrome经常显示多个请求,但是如果你从第二个开始检查,通常他们都会满意地使用缓存

如果要在JS代码中进行内部缓存,请尝试按URL缓存图像,如下所示:

// use this as JS cache
var images = {};

function loadCarousels(carouselLoc, carouselId) {

  $("li").find(carouselLoc).each(function (index) {
    var img = this;
    var outer = 0;

    // cache it
    if(!images[img.src]){
     images[img.src] = document.createElement("img");
     // if the user disable the cache, this should prevent another request
     images[img.src].src = img.src; 
    }

    $(carouselId).find("ul").each(function (innerIndex) {
        var liX = document.createElement("li");
        $(this).append(liX);
        // retrieve from the cache
        var imgInner = images[img.src];
        $(imgInner).appendTo(liX);
        console.log($(this));
    });
  });
}

大多数浏览器都会在catch中存储pic,所以这不应该是一个问题。我正在看到对Web服务器的多个请求,虽然这并不完全是您需要的,但是如果您可以使用图像作为背景,您可以拥有一个公共css类……您在哪里看到请求的图像?在Chrome的网络选项卡的HTML中。这些是基于数据库中url的图像。它就像一个摘要详细信息视图,我们在页面的两个位置显示图像