Last active
November 27, 2016 06:11
-
-
Save laverboy/7356665 to your computer and use it in GitHub Desktop.
Javascript Image Replacement technique in Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -------------------------------- | |
// 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') + ')'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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