Refresh image with a new one at the same url

后端 未结 19 3299
南旧
南旧 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:48

    Heavily based on Doin's #4 code, the below example simplifies that code a great bit utilising document.write instead of src in the iframe to support CORS. Also only focuses on busting the browser cache, not reloading every image on the page.

    Below is written in typescript and uses the angular $q promise library, just fyi, but should be easy enough to port to vanilla javascript. Method is meant to live inside a typescript class.

    Returns a promise that will be resolved when the iframe has completed reloading. Not heavily tested, but works well for us.

        mmForceImgReload(src: string): ng.IPromise {
            var deferred = $q.defer();
            var iframe = window.document.createElement("iframe");
    
            var firstLoad = true;
            var loadCallback = (e) => {
                if (firstLoad) {
                    firstLoad = false;
                    iframe.contentWindow.location.reload(true);
                } else {
                    if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
                    deferred.resolve();
                }
            }
            iframe.style.display = "none";
            window.parent.document.body.appendChild(iframe);
            iframe.addEventListener("load", loadCallback, false);
            iframe.addEventListener("error", loadCallback, false);
            var doc = iframe.contentWindow.document;
            doc.open();
            doc.write('');
            doc.close();
            return deferred.promise;
        }
    

提交回复
热议问题