Skip to content

Instantly share code, notes, and snippets.

@laverboy
Last active November 27, 2016 06:11
Show Gist options
  • Save laverboy/7356665 to your computer and use it in GitHub Desktop.
Save laverboy/7356665 to your computer and use it in GitHub Desktop.
Javascript Image Replacement technique in Wordpress
// --------------------------------
// load images from their data-src
// --------------------------------
// - pure javascript
for (var i = document.querySelectorAll('[data-src]').length - 1; i >= 0; i--) {
var image = document.querySelectorAll('[data-src]')[i];
image.src = image.getAttribute('data-src');
};
// - jQuery
$('[data-src]').each(function (){
$(this).attr('src', $(this).data('src'));
});
// --------------------------------
// load background images from their data-bg-src
// --------------------------------
// - pure javascript
for (var i = document.querySelectorAll('[data-bg-src]').length - 1; i >= 0; i--) {
var el = document.querySelectorAll('[data-bg-src]')[i];
el.style.backgroundImage = 'url(' + el.getAttribute('data-bg-src') + ')';
};
// - jQuery
$('[data-bg-src]').each(function () {
$(this).css('background-image', 'url(' + $(this).data('bg-src') + ')');
});
/**
* Replace image src with data-src for javascript image replacement
*/
function src_replace($html) {
$return = str_replace('src="', 'data-src="', $html);
return $return;
}
add_filter('the_content', 'src_replace');
add_filter('post_thumbnail_html', 'src_replace');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment