Including libraries with Script tags

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Including libraries with Script tags

You can include a library with <script> tags. If you choose this approach, make sure you include the library before your main JavaScript file.

<script src="library.js"></script>
<script src="main.js"></script>

Libraries linked this way will have the same global scope as your main JavaScript file. If your library contains global variables, these variables will be accessible inside your main JavaScript file.

// library.js
const hello = 'Hello World!'
// main.js
console.log(hello)
Logs hello variable in main.js file. Result: 'Hello World!'.

We don’t want variables to leak into global scope because they can cause naming conflicts with other libraries or with the main JavaScript file.

If you build a library that uses a <script> tag, you want to encapsulate your code so the variables don’t leak into the global scope.

How to encapsulate

There are three ways to encapsulate libraries:

  1. With a block scope
  2. With a function
  3. With an IIFE

If you’re building an Automatic Library, you can encapsulate code with block scopes or IIFE. Your code will be executed once the user includes your library into their project.

// Use block scope
{
  // All your code here...
}

// Or IIFE
(function () {
  // All your code here...
})()

If you’re building a Manual Library, you need to encapsulate your code with a function. Users will be able to call your function and assign the returned value (if any) into a variable.

// library.js
function libraryName () {
  // All your code here
}
// main.js
// Activates library
const result = libraryName()