HTML ยท Module 02 ยท Lesson 8 of 54

Linking External Stylesheets & Scripts

What are External Assets?

Think of a standard index page like an apartment blueprint. The blueprint itself is just lines showing the walls. To make it livable, you hire an interior designer to paint the walls (CSS) and an electrician to install working light switches and smart controls (JavaScript).

Instead of putting all of this code into one giant file, we link separate files together:

  • <link rel="stylesheet" href="...">: Connects a CSS file to add colors and styling.
  • <script src="..."></script>: Loads a JavaScript file to add interactivity (like clicks, calculations, or popups).
  • Why does it matter?

    Splitting structure (HTML), presentation (CSS), and behavior (JavaScript) into different files is called Separation of Concerns. It keeps your code organized, easier to maintain, and allows multiple pages to share the same stylesheet or script.

    How to write it

  • <link> tags for CSS belong in the <head> of your page.
  • <script> tags for JavaScript are usually placed right before the closing </body> tag (to make sure the HTML content loads first).
  • <head>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <!-- Page content here -->
      <script src="app.js"></script>
    </body>
    
    Link CSS
    Link Javascript

    Common Mistakes

  • Forgetting the closing tag on a script element: Unlike <link>, which is self-closing, <script> must always have a closing tag: <script src="file.js"></script>. Leaving it open can break your page rendering.
  • Forgetting the rel="stylesheet" attribute: If you write <link href="style.css"> without the rel attribute, the browser won't know the file is a stylesheet and won't apply your styles!
  • Quick Reference

  • <link rel="stylesheet" href="filename.css"> โ€” Connects CSS style rules.
  • <script src="filename.js"></script> โ€” Imports JavaScript functionality.
  • Your Task
    1. In the `<head>`, link an external stylesheet named 'theme.css' using `<link>`. 2. In the `<body>`, import an external script named 'main.js' using `<script>`.
    index.html
    Type code above to start the lesson.
    Live Preview