Home >Web Front-end >JS Tutorial >Two ways to import js files in Javascript

Two ways to import js files in Javascript

autoload
autoloadOriginal
2021-04-13 11:32:469921browse

Two ways to import js files in Javascript

In order to avoid displaying a large amount of code in HTML, we generally choose to put the js script into a separate file, and then js file is imported into HTML, which can make the HTML file more concise. This article mainly introduces two ways to import js script: : Traditional import, module import.

First confirm the location of the js script that needs to be imported. This article is in the same path as the HTML file.

1. Traditional import:

JS script content:

//文件名:example.js
let a="呵呵姑娘";

HTML content:

<!-- example.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./example.js"></script>
    <script> 
        console.log(a);
    </script>
</body>
</html>

2. Module import:

JS script content:

//文件名:example.js
let a="呵呵姑娘";
export {a};

HTML content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="module">
        import {a} from &#39;./example.js&#39;;
        console.log(a);
    </script>
</body>
</html>

Recommended: "2021 js interview questions and answers (large summary)"js tutorial

The above is the detailed content of Two ways to import js files in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn