patternjavascriptMinor
Renaming the iframe src attribute to facilitate lazy loading
Viewed 0 times
iframethesrcrenaminglazyattributeloadingfacilitate
Problem
I'm not great with javascript. I need some code to rename all iframe
Does this look OK? or is there a better way to achieve this. Any help appreciated?
src attribute names to data-src, for a lazyload plugin to work. I couldn't find out how to rename the attribute names, but with some trial and error I managed something similar and it is working OK: $( document ).ready( function() {
$( 'iframe' ).each(function() {
//store each iframe scr attribute value in a variable
var attr_value = $(this).attr("src");
//Add a data-src attribute with the src attribute value
$(this).attr('data-src', attr_value);
// remove the old src attribute
$(this).removeAttr('src');
});
});Does this look OK? or is there a better way to achieve this. Any help appreciated?
Solution
Calling
$(this) three times is a bit wasteful. You can improve that by taking advantage of $.attr(attributeName, function) and by using chaining.$(function() {
$('iframe').attr('data-src', function() { return $(this).attr('src'); })
.removeAttr('src');
});
// For demonstration...
$(function() {
$('#printout').text($('iframe').attr('data-src'));
});
data-src=
Context
StackExchange Code Review Q#121730, answer score: 3
Revisions (0)
No revisions yet.