5
\$\begingroup\$

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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 3, 2016 at 0:36
\$\endgroup\$
2
  • 1
    \$\begingroup\$ This code runs inside $(document).ready(...) — doesn't that mean that the iframes have already been loaded? \$\endgroup\$ Commented Mar 3, 2016 at 0:54
  • \$\begingroup\$ It doesn't seem to, I think it is different with iframes. My document is ready before the documents inside the iframes are ready. Isn't $( window ).load(function() {}) 4loc.wordpress.com/2009/04/28/documentready-vs-windowload the one for when everything has fully loaded? \$\endgroup\$ Commented Mar 3, 2016 at 1:29

1 Answer 1

3
\$\begingroup\$

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>

answered Mar 3, 2016 at 3:26
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.