I'm not great with javascript. I need some code to rename all iframe 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?
1 Answer 1
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'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
data-src=<span id="printout"></span>
<iframe width="10" height="10" src="http://codereview.stackexchange.com/"></iframe>
</body>
$(document).ready(...)
— doesn't that mean that the iframes have already been loaded? \$\endgroup\$