Главная страница » Чем src отличается от href

Чем src отличается от href

  • автор:

Русские Блоги

URL: сокращение от Uniform Resource Locators (Uniform Resource Locators), веб-браузер запрашивает страницу с веб-сервера через URL-адрес.
С точки зрения непрофессионала, URL — это строка, используемая для описания информационных ресурсов в Интернете, которая в основном используется в различных клиентских и серверных программах WWW, особенно в знаменитой Mosaic. URL-адрес может использоваться для описания различных информационных ресурсов в едином формате, включая файлы, адреса серверов и каталоги. Каждый файл в Интернете имеет уникальный URL-адрес. Базовый URL-адрес включает режим (или протокол), имя сервера (или IP-адрес), путь и имя файла, например «protocol: // authorization / path? Query». Полный общий синтаксис идентификатора ресурса с частью авторизации:
протокол: // имя пользователя: пароль@subdomain.domain имя домена верхнего уровня: номер порта / каталог / имя файла. суффикс файла? параметр = значение # знак
Формат URL состоит из следующих трех частей:
Первая часть — это соглашение (или называется методом обслуживания);
Вторая часть — это IP-адрес хоста, на котором хранится ресурс (иногда включая номер порта);
Третья часть — это конкретный адрес ресурса хоста. , Такие как каталог и имя файла и т. Д.
Первая часть и вторая часть разделены символом ": //", а вторая часть и третья часть разделены символом "/". Первая и вторая части являются обязательными, а третью часть иногда можно опустить

Что такое SRC?

src означает сокращение от источника, что означает импорт файлов. Цель состоит в том, чтобы загрузить файл на html-страницу. Когда браузер выполняет синтаксический анализ, он приостанавливает другое содержимое и сначала загружает содержимое src. Необходимо дождаться загрузки содержимого src. Позже будет казнено позже. Вот почему файл JS часто размещается в нижней части HTML-файла. Если вы поместили файл js в заголовок страницы, используйте: обработку событий window.onload. Браузер распознает документ как документ CSS, загружает документ параллельно и не прекращает обработку текущего документа. Это причина, почему ссылка рекомендуется.

Содержимое src является обязательной частью страницы. Содержимое, на которое указывает src, будет встроено в документ, в котором находится текущий тег. Обычно используется в: img, script, iframe. Например:

Что такое HREF?

href — это сокращение от Hypertext Reference, что означает гипертекстовую ссылку, указывающую на местоположение сетевых ресурсов, устанавливающую ссылку с текущим элементом (якорь) или текущим документом (ссылка), а его прямая связь со страницей является отношением ссылки. При загрузке сама страница не остановит загрузку другого контента. Используется для установления связи между текущим элементом и документом.

Обычно используется в ссылке, например:

подводить итоги:

Url не является атрибутом, src и href являются атрибутами, src используется для замены текущего элемента, href используется для установления соединения между текущим документом и ссылочным ресурсом, то есть путь, на который ссылается src, является путем загрузки, таким как img, и путем, на который ссылается href Это место для прыжка.

Чем src отличается от href

html, css, javascript

Last night, I vented out my frustration on < link > requiring href to point to a CSS stylesheet instead of src .

I will share the help I received and the history provided by wonderful folks, Brendan Eich (creator of JavaScript), and Håkon Wium Lie (creator of CSS) on Twitter.

href resources are loaded based on a trigger while src resources are loaded automatically.
Not 100% accurate because CSS files get loaded automatically.
The confusion between href and src is due to a historical reason in early web standards era.

Difference between "href" & "src"

src is for a request while href is for a link to a resource.

Being unable to grasp the difference, I replied that "CSS" is a request to download/parse/apply, it should be using src .

Brendan Eich kindly replied that src is for "auto inclusion" while href 'ed resources are loaded after an action occurs.

But as for CSS, he agreed that href for CSS "seems(ed) inconsistent".

link href

Håkon Wium Lie kindly provided the history (how) and the rationale (why) behind it.

The rationale was because the "HTML2 specification said so".

img src

And then Håkon followed up with how and why img uses src .

img . src was proposed by Marc Andreessen and Sir Tim Berners-Lee (inventor of World Wide Web) favored using an anchor tag with href !

As you can see it's more "convenient" to use img . src thus that's what's implemented.

There you have it. The convenience factor has won over. ��

Additional History — HTTP Referer

After sharing the Twitter thread in useReactNYC (a React Meetup in NYC) slack workspace, Donavon (one of the useReactNYC hosts and an active React community educator who loves to < . �� >) has shared a link on how an HTTP header referer (note it's not spelled as "referrer", missing one "r") misspelling came about.

SPOILER: An old spell checker didn't catch it.

Parting Words

Many thanks to Brendan Eich, and Håkon Wium Lie for the help and the hi/story.

It was a great experience as they spared their time to teach and share the experience.

You can check out the original thread (but be warned, it has many branches and thus could be hard to follow ��).

Чем src отличается от href

Где используется href

href может быть:

Используется для указания пути, в теге «а», по которому будет совершен переход — вместе будет называться ссылкой.

Вывод об отличиях между url, href и src

href — это атрибут ссылки, т.е. после нажатия мы перейдем по пути указанном в атрибуте href.

url — либо «type»(тип input), либо адрес css(например картинки) — подробнее

src — я бы назвал это мультимедиа, адрес на картинку, аудио, видео — подробнее

href и src — это атрибуты

Не забываем, что «src» используемый в css- это не атрибут, а дискриптор.

Основываясь на собственных знаниях

Перечислил все, что знал.

Возможно, что есть ещё какие-то способы использования всех трех значений.

Difference between SRC and HREF

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=»https://stackoverflow.com/questions/3395359/myscript.js» inside the script tag.
  • To refer an image file: src=»https://stackoverflow.com/questions/3395359/mypic.jpg» inside an image tag.
  • To refer another webpage: href=»http://www.webpage.com» inside an anchor tag.

15 Answers 15

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 of link ) and the destination anchor or resource defined by this attribute. When we write:

The browser understands that this resource is a stylesheet and the processing parsing 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 the style tag. (Hence it is advisable to use link rather than @import for 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 script tag. Similar is the case with img tag. It is an empty tag and the content, that should come inside it, is defined by the src attribute. The browser pauses the loading until it fetches and loads the image. [so is the case with iframe ]

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *