Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change src of image before request has been sent

I did a lot of research about this problem, but with no success. Essentially what I want to do is this:
1) Replace the src- attribute of all images with a placeholder, like 'blank.gif'
2) Add the HTML5 data-original attribute with the original image location
3) Lazyload the images (it needs the data-original attribute to work properly)

What I tried without success:
1) attaching this eventlistener document.addEventListener('beforeload', doBeforeLoad, true);
with this function

function beforeload() {
        var blank = 'image/location/images/blank.gif';
        $('img').each(function() {
            var orig = $(this).attr('src');
            $(this).attr('data-original',orig);
            $(this).attr('src',blank);
            console.log("changing all data on images");
        });
    }


2) on document.ready sure it won't work..


I have no idea if this is even possible, so any help | suggestion | resource would be greatly appreciated
PS: for example I want to make it work here) (because it's a image-heavy article )

like image 834
christian_fei Avatar asked Jan 19 '13 13:01

christian_fei


People also ask

Can you change img src?

Change Img src If you'd like to replace an image on your website, then you can simply change the image file path or URL in its source attribute. You can change this attribute at any time. It's important to note that the new image inherits the height and width attributes of the original image.

How do I remove the src from a photo?

To clear an image src attribute: Use the setAttribute() method to set the image's src attribute to an empty string. Alternatively, hide the image element.

How do I give an image an src?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.

Can CSS set src?

No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image .


1 Answers

The browser will start making the requests before you can start executing your JS. I recommend you alter the source html to be in the data pattern you require for lazy loading the images. This needs to happen before the browser receives it. This shouldn't be too much trouble if it's server generated.

like image 88
Paul Fleming Avatar answered Sep 28 '22 22:09

Paul Fleming