So, I am creating a website that will use a lot of animated GIFs on hover. There will be many images, and I only want to upload images that will be used on any given page. It uses WordPress, so I can only use conditional tags to indicate the URL of the images I need on a particular page.
My problem was how to tell the browser / server which images to preload. I decided to add an HTML5 data attribute to the contained element.
For example, I would have a DIV with this PHP in it:
<div id="home-container" class="preload" data-preload="<?php echo preloadImages(); ?>"></div>
To call this function in PHP:
function preloadImages() { global $post; $templateURL = get_template_directory_uri(); $images = array(); if( is_page('test') ) $images[] = "'".$templateURL."/images/gifs-static/button-info-tab-close-off.gif'"; $images[] = "'".$templateURL."/images/gifs-animated/button-info-tab-close.gif'"; } return implode(", ", $images); }
Thus, the output will be as follows:
<div id="home-container" class="preload" data-preload="'http://example.com/images/gifs-static/button-info-tab-close-off.gif', 'http://example.com/images/gifs-animated/button-info-tab-close.gif'"></div>
And then I run this JavaScript:
jQuery('.preload').each(function(){ var images = [ // Comma separated list jQuery(this).data('preload') ]; jQuery(images).each(function() { jQuery('<img />').attr('src', this).addClass('preloaded').appendTo('body').hide(); }); });
The problem is that JavaScript does not like comma-separated list. If I just write in the urls it works fine. So is there a better way to pass these URLs? Or is there a better way at all?
source share