2013-05-31 73 views
-1

我正在使用jQuery构建一个网站。 两件重要的事情:通过javascript更改图像src - 缓存问题

  1. 我想手动更改图片(图片src),但有时画面没有改变(我使用的是现在的铬,但我想一般的解决方案)。
  2. 此外,我想获得图片宽度+高度,我加载图片后。 (图片是来自服务器的文件 - 我只是使用不同的文件名)。

当通过JavaScript/jQuery改变图像 - 我意识到,当我改变图像一次,它保存在内存中,所以我遇到了一些问题。

我发现图像不上报的第二时间,由于缓存的问题,所以我做了一些解决方法,我意识到,我需要做的JavaScript命令,例如:

$("#id_image").attr("src", "pictures\\mypicture.jpg" + "?" + Math.random()); 

那怎么我我正在手动更改图像。

通过使用Math.random()我得到了第二个问题:

如果我Math.random()以前写的一行:

$("#id_image").width("auto"); 
$("#id_image").height("auto"); 

我没有得到使用Math.random()后高度+宽度,所以我把另一条线,最后我的代码是:

$("#id_image").width("auto"); 
$("#id_image").height("auto"); 
$("#id_image").attr("src", "pictures\\mypicture.jpg"); 
$("#id_image").attr("src", "pictures\\mypicture.jpg" + "?" + Math.random()); 
alert("#id_image").width()); // **** returns 0 sometimes due cache 
alert("#id_image").height()); // **** returns 0 sometimes due cache 

不过,我有一些问题(见Asterisk的话),我不知道该怎么总是获取加载图像的宽度+高度。

+1

问题是'width()'和'height()'在图像完成加载之前调用,因此为零。在'(“#id_image”).load()'处理程序中包含警报。 –

回答

4

你可以尝试设置图片src,这样,即使你的图像缓存之前设置onload处理,这应该给你正确的图像尺寸:

$("#id_image").on('load',function(){ 
    alert($(this).width()); 
    alert($(this).height()); 
}); 
$("#id_image").attr("src", "pictures\mypicture.jpg"); 
+0

很酷。 这是我应该参考宽度+高度的正确位置。 (否则,我可能得到width = height = 0,在它被计算之前,特别是当我引用“pictures \\ mypicture.jpg”+“?”+ Math.random()时,它总是返回width = height = 0。我以前的代码)。 谢谢:) – Eitan

+0

好的,我确实接受你的答案。 我不知道它是否是接受答案的选项。 – Eitan

+0

thx我欣赏 –

0
VersionNumber = System.Configuration.ConfigurationManager.AppSettings["Version"]; 

    //Caching Issues For JS 
    public static string JSVersionUpdate(string JsFile) 
    { 
     StringBuilder str = new StringBuilder(); 
     str.Append(GetQualifiedPath(JsFile)); 
     str.Append("?Version="); 
     str.Append(VersionNumber); 
     return str.ToString(); 
    } 

    public static void DiscardVersion() 
    { 
     VersionNumber = null; 
    } 

    //get Full Path for JS File 
    private static string GetQualifiedPath(string path) 
    { 
     var httpRequestBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); 

     path = path.Replace("~", string.Empty); 

     string appPath = string.Empty; 
     if (httpRequestBase != null) 
     { 
      //Formatting the fully qualified website url/name 
      appPath = string.Format("{0}://{1}{2}{3}{4}", 
         httpRequestBase.Request.Url.Scheme, 
         httpRequestBase.Request.Url.Host, 
         httpRequestBase.Request.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Request.Url.Port, 
         httpRequestBase.Request.ApplicationPath, 
         path); 
     } 
     appPath = appPath.TrimEnd('/'); 

     return appPath; 
    } 
} 

在UI页面:SCRIPT SRC =” JSVersionUpdate( “〜/脚本/应用/ Abc.js”)”

O/p:〜/脚本/应用/ Abc.js /版本=从服务器JS文件1.0

浏览器请求仅当版是不同的e它会缓存出来。现在我不需要告诉某人在部署后一次又一次清除缓存。只有我做的事情是我在Web COnfig中更改版本号。

同样可以应用于图像以及!希望它帮助