Search code examples
javascriptimagewordpresscachingdelay

Delay background image and stop it from being cached


I have a background image set to appear in place of/behind an ad slot, in case of ad blocking. However, I need to delay it until after the ad has shown.

I use the following code, however, the image is not delayed long enough.

<script type="text/javascript" language="JavaScript">
var resources = {div1:"url('/images/image1.png')",div2:"url('/images/image2.jpg')"};
function loadImageBG(id) {
  document.getElementById(id).style.backgroundImage = resources[id];
}
</script>


Also, how may I stop the image from being cached?

This is a WP site, and I'm using WP Super Cache; I see no function within the plugin to do this, though even so, I'm not sure this would be sufficient for browsers cache.


Solution

  • A simple, robust way would be a timer. Given the vagaries of unknown ad loading time -- and whether it loads at all -- it won't be perfect. But it's a lot simpler than trying to determine when or if the ad loads.

    Try something like:

    function loadImageBG (id) {
        setTimeout ( function () {
            document.getElementById (id).style.backgroundImage = resources[id];
        }, 888);
    }
    


    I recommend not trying to stop the cache; you don't want to annoy your users too much. ;)

    But, one way to do that is to append unique parameters to the resource URL:

    function loadImageBG (id) {
        setTimeout ( function () {
            var d           = new Date();
            var milliSecs   = d.getTime();
            var noCacheURL  = resources[id].replace (/'\)/, "?nc=" + milliSecs + "')");
    
            document.getElementById (id).style.backgroundImage = noCacheURL;
        }, 888);
    }
    

    Notes:

    1. 888 is the timer delay in milliseconds. For usability reasons, I recommend not making this larger than 1000 -- which is 1 second.

    2. There is no noCacheURL delay value. Because noCacheURLs value is set by the millisecond clock, it's value will always be different with every page load.

      Thus, the user's browser will always request a fresh copy, bypassing the user's cache.

      If you are using a dynamically generated image (seems doubtful) and caching that server-side, then its timeout is a different question that you would need to ask separately.