Preload Images
Here’s an easy way to manage your image preloads from anywhere in your PHP functions. We can simply build a globalized array of all image sources prior to outputting the page, then hook into the wp_footer action to output the required Javascript.
Each time your code encounters an image source that must be preloaded, simply call wpcx_add_preload_img($src) to add it to the preload queue.
This uses jQuery, but could easily be converted to standard Javascript.
// add an img src to the preload queue function wpcx_add_preload_img($src) { global $wpcx_preload_srcs; if (!is_array($wpcx_preload_srcs)) $wpcx_preload_srcs = array(); $wpcx_preload_srcs[] = $src; } // preload queued img srcs function wpcx_echo_preload_script() { global $wpcx_preload_srcs; if (empty($wpcx_preload_srcs)) return; if (!wp_script_is('jquery')) wp_enqueue_script('jquery'); ?> <script type="text/javascript"> /* <![CDATA[ */ jQuery().ready(function($){ $(<?php echo json_encode($wpcx_preload_srcs) ?>).each(function(){ $('<img />')[0].src = this; }); }); /* ]]> */ </script> <?php } add_action('wp_footer','wpcx_echo_preload_script');