Search code examples
javascripthtmllocalhosthttpserver

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


Why can't we just run the web app by running/opening the index.html?

Why does the file:///C:/[...address]/index.html not loading the css/js correctly like http://localhost:3000/?

enter image description here


Solution

  • Here are a few notes that we should consider:

    1- Diffrent Protocols

    I should mention that there are two protocols:

    1. File protocol which is prefixed by file:///
    2. HTTP(network) protocol which is prefixed by http://

    So they are two different protocols therefore the browsers treated them differently.

    2- Different path resolver

    Root relative links e.g. src="/js/modal.js" are available when using a server to run our app(to simply run the app on HTTP protocol)

    server based:

    <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

    file based:

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

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

    3- Cookies and local storage

    Based on 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.

    And Based on Mozilla and WikiPedia and IETF, Cookies are small blocks of data created by a web server while a user is browsing a website, So, it is strictly an HTTP mechanism which will be accessible when we use a web server to run our web app.

    4- CORS

    Based on Cross origin policy You can not send ajax request on file.

    finally

    There are quite a few features that I haven't listed here(e.g. service worker, and security features) That can't be used with file type.