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?

\$\endgroup\$
  • 1
    \$\begingroup\$ This code runs inside $(document).ready(…) — doesn't that mean that the iframes have already been loaded? \$\endgroup\$ – 200_success Mar 3 '16 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\$ – Andy Mar 3 '16 at 1:29
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>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.