What are all the differences between src and data-src attributes?
What are differences and consequences (both good and bad) of using either data-src
or src
attribute of img
tag? Can I achieve the same results using both? If so, when should be used each of them?
Solution 1:
The attributes src
and data-src
have nothing in common, except that they are both allowed by HTML5 CR and they both contain the letters src
. Everything else is different.
The src
attribute is defined in HTML specs, and it has a functional meaning.
The data-src
attribute is just one of the infinite set of data-*
attributes, which have no defined meaning but can be used to include invisible data in an element, for use in scripting (or styling).
Solution 2:
If you want the image to load and display a particular image, then use .src
to load that image URL.
If you want a piece of meta data (on any tag) that can contain a URL, then use data-src
or any data-xxx
that you want to select.
MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
Example of src
on an image tag where the image loads the JPEG for you and displays it:
<img id="myImage" src="http://mydomain.com/foo.jpg">
<script>
var imageUrl = document.getElementById("myImage").src;
</script>
Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:
<div id="myDiv" data-src="http://mydomain.com/foo.jpg">
<script>
// in all browsers
var imageUrl = document.getElementById("myDiv").getAttribute("data-src");
// or in modern browsers
var imageUrl = document.getElementById("myDiv").dataset.src;
</script>
Example of data-src
on an image tag used as a place to store the URL of an alternate image:
<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">
<script>
var item = document.getElementById("myImage");
// switch the image to the URL specified in data-src
item.src = item.dataset.src;
</script>
Solution 3:
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
Solution 4:
src will render the value immediately and it’s the default for images, videos using a single source and iframes.
data-src is used when lazy loading to prevent the default image from loading when the page loads. Most lazy loading libraries will use intersection observer and copy the data-src value to src when it’s time to load the image.