通过缓存问题更改图像src
Changing images src by cache issue
我正在使用jQuery构建一个网站。两件大事:
- 我想手动更改图片(image-src(,但有时图片不会更改(我现在使用chrome,但我想要一个通用的解决方案(
- 此外,我想在加载图片后获得图像宽度+高度。(图片是来自服务器的文件-我只是使用了不同的文件名(
当用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
尽管如此,我还是有一些问题(请参阅星号上的注释(,并且我不知道如何总是获得加载图像的宽度+高度。
您可以在设置图像src之前尝试设置onload处理程序,这样,即使您的图像被缓存,也会给您正确的图像大小:
$("#id_image").on('load',function(){
alert($(this).width());
alert($(this).height());
});
$("#id_image").attr("src", "pictures'mypicture.jpg");
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("~/Scripts/Application/Abc.js"(">
O/p:~/Scripts/Application/Abc.js/version=1.0
只有当版本不同时,浏览器才会从服务器请求JS文件,否则它将被缓存掉。现在我不需要告诉别人在部署后一次又一次地清除缓存。我唯一要做的就是更改Web配置中的版本号。
同样也可以应用于图像!!希望它能帮助
相关文章:
- Javascript将图像src更改为淡入淡出
- 在字符串中查找所有图像 src URL 并存储在数组中
- 如何使用javascript和xpath获取图像src
- 使用带有变量的javascript更改图像src
- 用jquery抓取图像SRC-attr
- MVC5更改jquery脚本中的图像src
- 隐藏或删除图像 src=未定义
- JavaScript 动态更改图像 src 的位置 - NO JQuery
- 如何使用 jquery、声音/静音按钮更改图像 SRC onclick
- 有没有一种方法可以判断图像src是否在javascript内部返回null
- 更改图像src-dons't工作jquery/js
- 将图像加载到localStorage,并将图像src设置到该位置
- 需要多次使用getElementById来更改图像src
- 如何更改多个图像的图像src
- 加载后修改页面上所有没有id的图像(src)
- 带有图像 src 的 JavaScript 点击事件
- 如果屏幕宽度 <= 699,则交换图像 src
- 更换部分图像 src
- 从没有jQuery的字符串中获取图像src
- 保存图像 src 的功能不起作用