The SRC and HREF attributes are used to include some external entities like an image, a CSS file, a HTML file, any other web page or a JavaScript file.
Is there a clear differentiation between SRC and HREF? Where or when to use SRC or HREF? I think they can’t be used interchangeably.
I’m giving below few examples where these attributes are used:
- To refer a CSS file:
href="cssfile.css"inside the link tag. - To refer a JS file:
src="myscript.js"inside the script tag. - To refer an image file:
src="mypic.jpg"inside an image tag. - To refer another webpage:
href="http://www.webpage.com"inside an anchor tag.
NOTE: @John-Yin’s answer is more appropriate considering the changes in the specs.
Yes. There is a differentiation between src and href and they can’t be used interchangeably. We use src for replaced elements while href for establishing a relationship between the referencing document and an external resource.
href (Hypertext Reference) attribute specifies the location of a Web resource thus defining a link or relationship between the current element (in case of anchor
a) or current document (in case oflink) and the destination anchor or resource defined by this attribute. When we write:The browser understands that this resource is a stylesheet and the
processingparsing of the page is not paused (rendering might be paused since the browser needs the style rules to paint and render the page). It is not similar to dumping the contents of the css file inside thestyletag. (Hence it is advisable to uselinkrather than@importfor attaching stylesheets to your html document.)src (Source) attribute just embeds the resource in the current document at the location of the element’s definition. For eg. When the browser finds
The loading and processing of the page is paused until this the browser fetches, compiles and executes the file. It is similar to dumping the contents of the js file inside the
scripttag. Similar is the case withimgtag. It is an empty tag and the content, that should come inside it, is defined by thesrcattribute. The browser pauses the loading until it fetches and loads the image. [so is the case withiframe]This is the reason why it is advisable to load all JavaScript files at the bottom (before the
</body>tag)update : Refer @John-Yin’s answer for more info on how it is implemented as per HTML 5 specs.