0

In order to use most lazy loading libraries we need to use "data-src" instead of just "src" How can i modify the html and "src" to be data-src to be able to use lazy loading.

I CANT change the html code to data-src because we sharing components and what this change only on one page.

So my question is, once i do view page source i want to see the data-src instead of just src

I was able to edit the DOM and see my changes in view page source when i used this line of code


$("a[href='/comprehensive-insurance-and-collision-coveragee']").prop('href', '/comprehensive-insurance-and-collision-coverage')

it basically edited the link of from coveragee to coverage. and when i did view page source i can see the link as coverage not coveragee,

i want to the same thing as that but for src to data-src

2 Answers 2

2

You can’t, since JavaScript makes changes to the DOM: there are several ways to change the attribute from src to data-src, but you won’t see it right in the sources. You can only see it inspecting the page with the browsers’ developer tools. You need back-end languages such as PHP to automatically make a server-side change.

In jQuery:

var source = $(element).attr("src");
$(element).attr("data-src", source).removeAttr("src");

In vanilla JavaScript:

var element = document.getElementById("id");
var source = element.getAttribute("src");
element.setAttribute("data-src", source);
element.removeAttribute("src");

But you can’t directly change the page sources. Changes stay in the DOM, so I guess this won’t work for lazy loading. You should consider a server-side language to make changes to that page, IMHO, unless the libraries are loaded after a script like those.

Sign up to request clarification or add additional context in comments.

3 Comments

I was about halfway through a similar answer lol. Basically, since the src is already loaded as a visible object, the HTTP request is already made, negating the benefits of lazy loading.
can you look at my update, i have changed the javascript in the past and in view page source i see the change as well.
If it works in view-sources too, then the first jQuery snippet should do the trick! Just remember to do it in an onload statement.
0

In case that you don‘t want to modify the src-attribute as it‘s being used in different contexts, you could add the loading=lazy attribute instead to lazy load images (and iframes if needed). Additionally to support older browsers as well, you could use the polyfill that I‘ve developed for this aspect: https://github.com/mfranzke/loading-attribute-polyfill

Comments

Your Answer

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.