我可靠的preLOAD和如何缓存在我的网站我的ajax加载图片? [英] How can I reliably preload and cache my ajax loading image across my site?

查看:161
本文介绍了我可靠的preLOAD和如何缓存在我的网站我的ajax加载图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了以下code到我的asp.net MVC的页面的Site.Master的目标是确保这一形象被载入前期和缓存(因为我用它在我的网站):

  $(文件)。就绪(函数(){        变种x =新的图像();
        x.src =/content/images/ajax-loader.gif;

我假定这code将迫使这个AJAX加载图像的preLOAD和高速缓存,但是当我运行一个页面引用这个形象,我仍然可以看到这几秒钟。这里是一个jqGrid的负载分区的一个例子

使用这种code为loadtext

  $ .jgrid = $ .jgrid || {};
 $ .extend($。jgrid,{
   默认值:{
    recordtext:观{0} - {1} {2},
    emptyrecords:没有记录查看,
    loadtext:正在加载数据...< IMG SRC =/内容/图片/ AJAX-loader.gif/>中,
    pgtext:页面{0} {1}
},

在我的实际加载的AJAX图像显示如下图所示:

时有尝试使用它之前加载和缓存任何建议什么可能会造成这一点,如何保证这个形象?是我的解决方案,每次实际重新下载该文件?

什么是最好的建议,这里如何实现我的目标?


解决方案

您使用 IMG 元素,浏览器会要求从服务器。使用 CSS 背景图片 后,将请求图像的只有一次,然后你可以用它多次,没有看到再这个问题。

\r
\r

.loading {\r
  显示:inline-block的;\r
  宽度:16px的;\r
  高度:16px的;\r
  背景:网址(http://i.stack.imgur.com/CRmPi.gif);\r
}

\r

< D​​IV>的Hello World<跨度类=加载>&LT ; / SPAN>< / DIV>\r
< D​​IV>的Hello World<跨度类=加载>< / SPAN>< / DIV>\r
< D​​IV>的Hello World<跨度类=加载>< / SPAN>< / DIV>

\r

\r
\r

I added the following code to my asp.net-mvc site.master page with the goal is making sure this image gets loaded upfront and cached (as I use it all over my site):

    $(document).ready(function () {

        var x = new Image();
        x.src = "/content/images/ajax-loader.gif";

I am assuming this code would force a preload and cache of this ajax loading image but when i run a page that references this image, i still see this for a few seconds. Here is an example of a jqgrid loading div

which uses this code for loadtext:

 $.jgrid = $.jgrid || {};
 $.extend($.jgrid,{
   defaults : {
    recordtext: "View {0} - {1} of {2}",
    emptyrecords: "No records to view",
    loadtext: "Loading Data ...<img src='/Content/Images/ajax-loader.gif' />",
    pgtext : "Page {0} of {1}"
},

before my actual ajax loading image shows like below:

Is there any suggestion for what could be causing this and how to ensure this image is loaded and cached prior to trying to use it? Is my solution actually redownloading the file each time?

What is the best recommendation here for how to achieve my goal?

解决方案

Whenever you use an img element, the browser will request it from server. Using CSS background-image, will request the image only once, and you can use it multiple times, without seeing that problem again.

.loading {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url(http://i.stack.imgur.com/CRmPi.gif);
}

<div>Hello World <span class="loading"></span></div>
<div>Hello World <span class="loading"></span></div>
<div>Hello World <span class="loading"></span></div>

这篇关于我可靠的preLOAD和如何缓存在我的网站我的ajax加载图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆