Is it possible to change the src = "" image before loading the original image

I am looking at Javascript that can change the src of an image. I'm just wondering if this can be done before the browser tries to get the original image.

Example.

Src="Large-Image"

      

Can I (with javascript, I would guess .. node.JS maybe?) Serve the user src="smaller-image"

?

Obviously, there will be no performance gain if the browser loads a large image first.

+3


source to share


4 answers


I don't think so, JS needs the image-tag to be available to access the attributes, so it must be executed later than that (for example, on the Ready document or placed after the tag), but at this point the browser has already started loading the image.

However, I've seen solutions where you don't set the url in the "src" attribute, but in a different attribute name like "data-src". Your Javascript can dynamically set this URL to the "src" attribute to force the browser to start loading.



For example (assuming jQuery is loaded):

<img data-src="http://www.url.nl/image.png" />

<script>
    $("img").each(function (index, element) {
       var $element = $(element);
       var imageUrl = $element.attr("data-src");

       //Do your checks here to change the image-url to a smaller one when required

       $element.attr("src", imageUrl);
    });        
</script>

      

+4


source


If I understand the jquery ready, ready function correctly , you should be able to achieve what you want.

"The handler passed to .ready () will execute after the DOM is ready, so this is generally the best place to attach all other event handlers and run other jQuery code."

On the other hand, load says



"In cases where code uses loaded assets (for example, if image dimensions are required), the code should instead be placed in a handler for the load event."

So, according to the prepared docs, it is called before the images are loaded, but if you can block the loading and change the image paths, there can only be a test response.

+1


source


You might be able to do this, but not reliably, and you can't leave a blank space src

if you want to output valid markup, so it might hurt mobile performance more than it helps.

Rather than reinventing the wheel, there are several ways to interact with clients and servers that don't rely on JS (which you can't guarantee will be included). They would all be more robust and standards-compliant (for example, for orientation in a CSS environment), which will give you better results.

0


source


Simple solution, not overly elegant in any way. Call your function to change the source of the image with the onload event.

<img id="YourID" src="PathToFirstImage" onload="YourFunction()">

      

While this changes the image after it is loaded, as long as the browsing browser is not insanely slow, your audience will never see the original image.

0


source







All Articles