What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me.

Why do we use

<script src="min.js"></script>
and
<link rel="stylesheet" href="min.css">
? Why not simply use
<style href="min.css"></style>
? Why is the link tag used for external CSS, but when writing CSS within the <head>, we use <style>...</style> instead?

I explained that it's because of specifications. Is there any additional information I could provide to him?

Answer №1

It's fascinating how history can sometimes be full of coincidences, isn't it? I would suggest checking out the section on the Past of diveintohtml5.info, where you can read about some interesting stories and mail correspondences among web developers. These developers were actually instrumental in creating the Web as we know it today ;)

For example, consider the <img> tag that we commonly use:

<IMG SRC="file://foobar.com/foo/bar/blargh.xbm">

which could have been:

<ICON name="NoEntry" href="http://note/foo/bar/NoEntry.xbm">

or

<A HREF="..." INCLUDE>See photo</A>

or

<INCLUDE HREF="...">

However, the developers ultimately decided to stick with <img>, as it was already implemented:

We’re not prepared to support INCLUDE/EMBED at this point. … So we’re probably going to go with (not ICON, since not all inlined images can be meaningfully called icons). For the time being, inlined images won’t be explicitly content-type’d; down the road, we plan to support that (along with the general adaptation of MIME). Actually, the image reading routines we’re currently using figure out the image format on the fly, so the filename extension won’t even be significant.

I may not have a direct answer to your question, but I'm also intrigued by the <link> tag. Finding the answer might involve some digging through web archives.

Answer №2

The viewpoint of the W3C reveals a distinction.

An <style> element presents a set of CSS rules that impact the current document. However, external style sheets are viewed as complete documents linked to the present page, and browsers have the discretion to disregard such documents based on the type and media attributes of the link. For example:

<link rel="stylesheet" type="text/css" media="screen" href="screen.css" />
<link rel="stylesheet" type="text/css" media="print" href="print.css" />

In this scenario, browsers typically only follow one of the links, either the screen (for regular display) or the print (for printing). The goal was to save bandwidth by downloading only the necessary resource, rather than fetching everything and sorting by media type later.

This is explicitly stated in the specification:

When the LINK element connects an external style sheet to a document, the type attribute specifies the stylesheet language and the media attribute defines the intended display medium or mediums. Browsers can optimize load times by pulling from the network only those stylesheets relevant to the current device.

Answer №3

The similar meanings of both attributes highlight a quirk in HTML where inconsistencies exist due to the influence of different browser implementations. This discrepancy arose because various browsers introduced attributes in different tags, leading the W3C to preserve some discrepancies for backward compatibility purposes.

Elements that utilize src:

script img iframe input video frame

Elements that make use of href: a link base

Answer №5

The <link> tag serves the purpose of connecting other files to the current one, defining its relationship or rel attribute.

In addition to linking documents, you can also utilize the <link> tag to connect other elements to your webpage. For example, including favicons:

<link rel="shortcut icon" href="favicon.ico" />

Answer №6

A potential explanation for the difference between using link ref and style:

The link tag is restricted to the head section, where "Metadata content" is typically found.

In contrast, prior to HTML5, the style tag was not permitted in the body, except with scoped. This made the choice between link ref and style src quite arbitrary.

Interestingly, external scripts could be included in the body before HTML5, leading to the necessity of script src. To streamline this process, allowing script in the head (where it was already accepted) while prohibiting link rel=script to prevent redundancy seemed like a logical decision.

Evidently, Tim Berners-Lee envisioned all aspects of web development being carried out with just the <a: https://example.com!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrollable horizontal card list using Bootstrap

Looking to design a unique layout featuring a horizontal list of cards where 3 cards are displayed simultaneously, with the ability to horizontally scroll through the rest, like this: https://i.sstatic.net/KgX27.png While achieving this using CSS is stra ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

The Epub text box feature is malfunctioning

I have a quiz task in an epub format where users need to enter their answers in a text box after reading the question. However, I am facing an issue where the text box does not display the keyboard for typing the answer. Is there a solution using javascr ...

Extract data from input field and transfer to another page using ajax without needing to submit the form

My form includes an email input field: <input type="email" id="email" name="email"/> There is also a verify button: <span style="cursor:pointer"> <p id="verify">Verify</p> </span> Upon clicking the verify button, a new in ...

Access the freshly launched URL

I am relatively new to PHP and have a table displayed on my webpage. Each row in the table has an auto-incremented rowid that is not being displayed. When clicking on a row, it opens a new page in the format of www.newpage.com/newpage/rowid. If I inspect ...

Difficulty encountered in assigning a value to a variable when utilizing an async function in Node.js

While attempting to retrieve the jwtauthtoken from the user and passing it to a function called getUserId() in the imported JavaScript file, I encountered an issue where the returned value was undefined instead of the decoded ID. The getUserId() function ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: https://i.sstatic.net/irTju.png Below is the code snippet: import React, { useState, Fragment } from "react"; import S ...

What is the best way to prevent a fetch request from being initiated before the authentication token has been received

After successfully logging in, the data request fetch function needs to send the request with the saved token bearer. However, the data fetch is not waiting for the token and is receiving an Unauthorized access code. This is how my data request fetch func ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

next-pwa seems to be malfunctioning without any discernible errors in the production environment

The repository is publicly available // next.config.js const withPWA = require("next-pwa"); module.exports = withPWA({ pwa: { dest: "public", sw: '/sw.js' }, }); _document.js _app.js Live I have verified the fu ...

Alignment of images at the center within a container div while maintaining a height of 100%

Apologies if this question has already been addressed - I have tried numerous methods to center images horizontally without success. This particular image just does not want to align in the center! For reference, here is the JSFiddle link HTML: (Please n ...

Exploring Angular's capabilities with filtering and handling $http promises

Having an issue with filtering data from a JSON file that contains an array of 20 objects. Within my factory, I have implemented two functions: function fetchData() { return $http .get('mock.json') .success(_handleData) ...

Encircling the icon with a circle

My styling skills are limited, but I'm attempting to create a marker that resembles the image linked below: https://i.stack.imgur.com/wXkaq.png. So far, I've made some changes in the code snippet provided, but I'm struggling to get it to d ...

Is there a way for my box to avoid reaching the bottom of the page?

Is there a way to prevent my box from reaching the bottom of the page? I am currently using Bootstrap 4 and have tried the spacing utilities, but they don't seem to be effective. https://i.sstatic.net/YRqb4.png Attached is a picture showing that the ...

I am utilizing Python Django to display a message from a Python file in HTML. While the current code is functional, I would like the message to be showcased as a pop-up or alert notification

Using Python Django. The message is coming from a Python file and I would like to display it in HTML. The current code is functioning, but I would like the message to appear as a pop-up or alert. Register {% if messages %} {% for result in messages %} < ...

Using Selenium and Python to scrape text from a continuously refreshing webpage after each scroll

Currently, I am utilizing Selenium/python to automatically scroll down a social media platform and extract posts. At the moment, I am gathering all the text in one go after scrolling a set number of times (see code below), but my objective is to only gathe ...

Using an object method within a different object in JavaScript

I am attempting to create two objects, one from each of my classes - a Person object and a Drink object. I then want to invoke the drinking method by passing in a Drink object. However, I am struggling with how to do this. Here is my code, and I can't ...

Learning to implement $first in an Angular ng-repeat to dynamically add a new table row

I am currently facing an issue with displaying a Google map for addresses in my Angular application. The problem seems to be related to the asynchronous nature of HTML and JS, but I am struggling to find a solution. The issue is that even though the map vi ...