Refresh image with a new one at the same url

后端 未结 19 3295
南旧
南旧 2020-11-21 22:00

I am accessing a link on my site that will provide a new image each time it is accessed.

The issue I am running into is that if I try to load the image in the backgr

19条回答
  •  抹茶落季
    2020-11-21 22:56

    I had a requirement: 1) can't add any ?var=xx to the image 2) it should work cross-domain

    I really like the #4 option in this answer with one but:

    • it has problems working with crossdomain reliably (and it requires touching the server code).

    My quick and dirty way is:

    1. Create hidden iframe
    2. Load the current page to it (yeah the whole page)
    3. iframe.contentWindow.location.reload(true);
    4. Re-set the image source to itself

    Here it is

    function RefreshCachedImage() {
        if (window.self !== window.top) return; //prevent recursion
        var $img = $("#MYIMAGE");
        var src = $img.attr("src");
        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        window.parent.document.body.appendChild(iframe);
        iframe.src = window.location.href;
        setTimeout(function () {
            iframe.contentWindow.location.reload(true);
            setTimeout(function () {
                $img.removeAttr("src").attr("src", src);
            }, 2000);
        }, 2000);
    }
    

    Yeah, I know, setTimeout... You have to change that to proper onload-events.

提交回复
热议问题