What are the differences between the src and data-src attributes?

What are the differences and consequences (both good and bad) from using the data-src or src attribute of the img tag? Can I achieve the same results with both? If so, when should each be used?

+70
html html5 image
Mar 10 '13 at 7:42
source share
5 answers

The src and data-src attributes have nothing in common, except that both are HTML5 CR enabled and both contain the letters src . Everything else is different.

The src attribute is defined in the HTML specifications and has a functional meaning.

The data-src attribute is just one of the endless sets of data-* attributes that do not have a specific value, but can be used to include invisible data in an element for use in scripts (or styling).

+129
Mar 10 '13 at 8:25
source share

If you want the image to load and display a specific image, use .src to load that image URL.

If you need some of the metadata (for any tag) that may contain a URL, use data-src or whatever data-xxx you want to select.

MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset

An example of src in an image tag, where the image loads a JPEG for you and displays it:

 <img id="myImage" src="http://mydomain.com/foo.jpg"> <script> var imageUrl = document.getElementById("myImage").src; </script> 

The example "data-src" on a tag without an image where the image has not yet been loaded is just a fragment of the metadata in 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> 

An example of data-src in an image tag used as a place to store the alternate image URL:

 <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> 
+13
Mar 10 '13 at 7:56
source share

The first <img /> invalid - src is a required attribute. data-src is an attribute that can be used, for example, for JavaScript, but has no representation.

+2
Mar 10 '13 at 7:46
source share

the data-src attribute is part of the data- * attribute collection provided in HTML5. data-src allows us to store additional data that does not matter to the browser, but that can be used in Javascript Code or CSS.

0
Oct 19 '17 at 18:39 on
source share

Well, the data src attribute is only used for data binding, such as ASP.NET ...

w3School src attribute

datasrc attribute for MSDN

-3
Mar 10 '13 at 7:50
source share



All Articles