Note that there are some explanatory texts on larger screens.

plurals
  1. POPreloading images using PHP and jQuery - Comma separated array?
    primarykey
    data
    text
    <p>So I'm building a website that will use a lot of animated GIF's on mouse hover. There will be a lot of images, and I only want to load the images that will be used on any given page. It's using WordPress so I can use the conditional tags to only put out the URL's of the images I need on a certain page.</p> <p>My problem was how to tell the browser/server which images needed to be preloaded. I decided to add a HTML5 data attribute to the containing element.</p> <p>For example, I would have a DIV with this PHP in it:</p> <pre><code>&lt;div id="home-container" class="preload" data-preload="&lt;?php echo preloadImages(); ?&gt;"&gt;&lt;/div&gt; </code></pre> <p>Which would call this function in PHP:</p> <pre><code>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); } </code></pre> <p>So the output would be this:</p> <pre><code>&lt;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'"&gt;&lt;/div&gt; </code></pre> <p>And then I run this JavaScript:</p> <pre><code>jQuery('.preload').each(function(){ var images = [ // Comma separated list jQuery(this).data('preload') ]; jQuery(images).each(function() { jQuery('&lt;img /&gt;').attr('src', this).addClass('preloaded').appendTo('body').hide(); }); }); </code></pre> <p>The problem is that the JavaScript does not like the comma separated list. If I just write in the URLs, it works fine. So is there a better way to pass in those URLs? Or a better way in general?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload