Reputation: 1103
I am struggeling to understand how exactly browsers are handling ES6 modules. I thought, that modules will only be executed the first time they are imported([modules: javascript.info][1].
Let's say i have following project structure:
js
admin.js
customers.js
index.js
customers.html
index.html
Both index.js
and customers.js
import the same module admin.js
. When i import index.js
in index.html
the name of admin
is changed from "John" to "Pete" and logged as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Modules</title>
</head>
<body>
<nav><a href="customers.html">Customers</a></nav>
<h1>Homepage</h1>
<script type="module" src="js/index.js"></script>
</body>
</html>
In customers.html i expected the admin's name to be "Pete" as well:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Customers</title>
</head>
<body>
<nav><a href="index.html">Home</a></nav>
<h1>Customers</h1>
<script type="module" src="js/customers.js"></script>
</body>
</html>
But instead of "Pete", "John" is logged again.
Modules i used:
// admin.js
export let admin = {
name: "John",
};
//index.js
import { admin } from "./admin.js";
admin.name = "Pete";
console.log(admin.name); // Pete
// customers.js
import { admin } from "./admin.js";
console.log(admin.name); // Pete
[1]: https://javascript.info/modules-intro#a-module-code-is-evaluated-only-the-first-time-when-imported)
Upvotes: 0
Views: 684
Reputation: 5432
As Felix said above, each page render/rerender would then reload all assets. This is the difference between a Single Page Application and a Multi Page Application. You're working with an MPA, so you would need some form of data persistence between pages, such as databasing the data server side and requesting it on each page load, or placing the necessary persisted data in something like localStorage
or sessionStorage
for access between pages.
Upvotes: 2