通过缓存问题更改图像src

Changing images src by cache issue

本文关键字:图像 src 问题 缓存      更新时间:2023-09-26

我正在使用jQuery构建一个网站。两件大事:

  1. 我想手动更改图片(image-src(,但有时图片不会更改(我现在使用chrome,但我想要一个通用的解决方案(
  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

尽管如此,我还是有一些问题(请参阅星号上的注释(,并且我不知道如何总是获得加载图像的宽度+高度。

您可以在设置图像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配置中的版本号。

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