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).
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>
Well the data src attribute is just used for binding data for example ASP.NET ...
data-src attribute is part of the data-* attributes collection introduced in HTML5. data-src allow us to store extra data that have no meaning to the browser but that can be use by Javascript Code or CSS rules.
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.
Source: Stackoverflow.com