【问题标题】:How to change img src on document ready before browser downloads images?如何在浏览器下载图像之前更改文档准备好的 img src?
【发布时间】:2010-09-17 22:40:40
【问题描述】:

在我的页面上,我在 thisdomain.com/images 上有一些图片。在 document.ready() 上,我将图像的 src 属性更改为 thatdomain.com/images。 Firebug 的“网络”选项卡显示图像是从 thisdomain.com 和 thatdomain.com 下载的。如何阻止浏览器从 thisdomain.com 下载图片?

$(document).ready(function(){
    $("img").each(function() {
        var $img = $(this);
        var src = $img.attr("src");
        $img.attr("src", src.replace(/thisdomain.com.com\/images/i, "thatdomain.com\/images"));
    });
});

编辑:ASP.NET 服务器端使用代码“在前面”覆盖 Render(),即

<script runat="server">        
    static Regex rgx = new Regex(@"thisdomain.com/images", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {   
        using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
        {   
            base.Render(htmlwriter);
            string html = htmlwriter.InnerWriter.ToString();

            string newHtml = rgx.Replace(html, "thatdomain.com/images");
            writer.Write(newHtml.Trim());
        }
    }
</script>

【问题讨论】:

    标签: asp.net jquery


    【解决方案1】:

    这听起来似乎不可能可靠地实现,因为一旦指定了 src,图像就会开始异步加载。

    我想不出解决方法。 &lt;base&gt; 标签将允许某种“大规模重定向”,但 URI 必须是相对的才能起作用。

    我确定您首先有输出 thisdomain.com 的理由,但我很确定您必须更改代码,以便改为输出 thatdomain.com(或不指定 src如果你想要一个 100% 防水的解决方案,你可以使用 jQuery 添加它们。

    【讨论】:

      【解决方案2】:

      这在客户端是行不通的。您最好的选择是服务器端解决方案。让服务器端脚本(PHP?JSP?ASP?等)读取要包含的 HTML 源代码,并在合适的 DOM 解析器的帮助下相应地替换 src,然后再将其发送到客户端。

      【讨论】:

      • 天哪,我没有看到你已经在评论中自己发布了它,@Vince。
      • @Vince:我会使用String.Replace() 而不是正则表达式。
      • 谢谢。我用秒表计时,而我的静态编译正则表达式表现不佳。也许取决于输入字符串的长度,静态编译的正则表达式最终会更好,但在我的情况下不是。
      • 您需要逐个字符替换,而不是逐个模式或字符替换。那么正则表达式永远不会击败普通的String.Replace()
      【解决方案3】:

      我不认为这是可能的。要使用 jQuery 函数,需要下载 jQuery 库,这可能意味着浏览器已经开始下载其他资源,例如图片。

      【讨论】:

        【解决方案4】:

        在元素被解析后,您不能完全确定通过更改 URL 来阻止下载。您可以获得的最接近的可能是在元素之后立即更改它:

        <img id="something" src="http://www.thisdomain.com/images/hello.gif" />
        <script type="text/javascript">
        var $img = $('#something');
        $img.attr("src", $img.attr("src").replace(/thisdomain.com\/images/i, "thatdomain.com\/images"));
        </script>
        

        【讨论】:

        • @BalusC:那肯定不行。这是尽可能接近的。
        【解决方案5】:

        我认为没有办法在页面加载后停止来自 img 元素的 GET 请求。很难提出替代方案,因为我不确定您要达到的目标。

        你能说得更具体些吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-11
          • 2015-06-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多