liveBook · Manning

Script element

As explained in Web Components in Action

An HTML element that embeds executable code or references an external script file for a document.

A script element loads JavaScript from an external file, keeping an HTML document easier to read and maintain as components grow. section 5.1

Use script elements to:

  • Load a Web Component such as a photo carousel with <script src="photocarousel.js"></script>. section 5.1
  • Add multiple component dependencies during development, then reduce production references by concatenating JavaScript into one build file. section 5.1
  • Move implementation code out of index.html while keeping component markup in the document body. section 5.1

Loading a photo carousel

Place <script src="photocarousel.js"></script> in the head, then use <wcia-photo-carousel> in the body with title, author, and photos attributes. The component can keep its CSS internally when eliminating a separate stylesheet reference. section 5.1

Listing 5.1. Example of loading Web Components with the <script> tag
<html>
<head>
   <meta charset="UTF-8">
   <title>Script Source for Loading Web Components</title>
   <script src="photocarousel.js"></script>                  #1
   <link href="photocarousel.css"
         rel="stylesheet"
         type="text/css"/>                                   #2
</head>
<body>
   <wcia-photo-carousel
           title="Future Vacation Photos"
           author="Ben Farrell"
           photos="https://i.imgur.com/fBmIASF.jpg,https://i.imgur.com/
           3zxD6rz.jpg,https://i.imgur.com/nKBgeLOr.jpg,https://
           i.imgur.com/yVjJZ1Yr.jpg">
   </wcia-photo-carousel>
</body>
</html>

Browse the complete HTML listing showing an external script loading a Web Component alongside its stylesheet. section 5.1

How Web Components in Action covers it

How deep it goes
Demonstrates single and multiple references, production concatenation, and dependency reduction without explaining script execution timing.
Examples
Uses a photo carousel, development HTML with many component references, and a production build.js reference.
What it assumes
Assumes familiarity with HTML documents, component markup, and external JavaScript and CSS files.
What you can do after
Apply it via HTML to load component code and organize development or production dependencies.
How it connects
Connects HTML, JavaScript, CSS, Web Components, external files, and build processes.

Also explained in

Compare how 3 books explain script element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.