为什么我们需要 运行 用于 运行 纯 html/css/js 应用程序的本地服务器?

Why do we need to run a local server for running a pure html/css/js app?

为什么我们不能 运行 running/opening index.html 的网络应用程序?

为什么 file:///C:/[...address]/index.html 没有像 http://localhost:3000/ 那样正确加载 css/js

以下是我们应该考虑的一些注意事项:

1- 不同的协议

我应该提到有两个协议:

  1. File protocolfile:///
  2. 为前缀
  3. HTTP(network) 前缀为 http://
  4. 的协议

所以它们是两种不同的协议,因此浏览器对它们的处理方式不同。

2- 不同的路径解析器

根相关链接,例如src="/js/modal.js" 在使用服务器 运行 我们的应用程序时可用(简单地 运行 HTTP 协议上的应用程序)

基于服务器:

<a href="home.html">Home</a> -> http://127.0.0.1:5500/home.html

<a href="/home.html">Home</a> -> http://127.0.0.1:5500/home.html

基于文件:

<a href="home.html">Home</a> -> file:///C:/Users/MyUser/Desktop/home.html

<a href="/home.html">Home</a> -> file:///C:/home.html

3- Cookie 和本地存储

基于Mozilla

localStorage data is specific to the protocol of the document. In particular, for a site loaded over HTTP (e.g., http://example.com), localStorage returns a different object than localStorage for the corresponding site loaded over HTTPS (e.g., https://example.com).

For documents loaded from file: URLs (that is, files opened in the browser directly from the user’s local filesystem, rather than being served from a web server) the requirements for localStorage behavior are undefined and may vary among different browsers.

In all current browsers, localStorage seems to return a different object for each file: URL. In other words, each file: URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn’t rely on it because, as mentioned above, the requirements for file: URLs remain undefined. So it’s possible that browsers may change their file: URL handling for localStorage at any time. In fact some browsers have changed their handling for it over time.

并且基于Mozilla and WikiPedia and IETFCookies是用户浏览网站时网络服务器创建的小数据块,因此,它严格来说是一种HTTP机制,当用户浏览网站时可以访问我们使用网络服务器 运行 我们的网络应用程序。

4-CORS

基于 Cross origin policy 您无法在 file 上发送 ajax 请求。

终于

有很多我没有在这里列出的功能(例如 service worker 和安全功能)不能与 file 类型一起使用。