How to reload the browser window when you save a file
By Flavio Copes
Learn how to automatically reload the browser whenever you save a file in a plain HTML and JS project, by installing and running the browser-sync tool.
The quickest way I found to reload the browser every time you save a file is browser-sync. You install it once, run a single command in your project folder, and the page refreshes on every change.
I was working on a website in vanilla HTML + JS, and I missed one of the best features provided by those quick start packages like create-react-app or the Vue CLI: reloading the page when I saved a file in the code editor.
Those tools ship a dev server with live reload built in. In a plain HTML project, you have nothing. You edit, switch to the browser, hit reload, switch back. Dozens of times per hour. browser-sync removes that loop.
Setting up browser-sync
Install it globally:
npm install -g browser-sync
then run it in your project folder:
browser-sync start --server --files "."
--server starts a static web server on port 3000, serving the current folder. --files "." tells it what to watch for changes: everything in the current folder and all subfolders.
The command also opens a browser window pointing to http://localhost:3000. Any time you change a file, the browser refreshes.
Very useful while prototyping!
How does the reload work?
browser-sync injects a small script into every HTML page it serves. That script opens a WebSocket connection back to the server. When a watched file changes, the server pushes a message and the script reloads the page.
CSS gets special treatment: browser-sync injects the new styles without a full page reload, so you keep your scroll position and page state.
Watching fewer files
Watching "." is fine for a small folder. But if your project contains a node_modules folder, every change in there triggers a reload too, and startup gets slower because there are thousands of files to watch.
You can pass specific patterns instead:
browser-sync start --server --files "*.html, css/*.css, js/*.js"
Now only your own files trigger the refresh.
One pitfall
The injected script needs a <body> tag to hook into. If you’re testing a bare HTML fragment without a proper <body>, browser-sync can’t inject its snippet and the page never auto-reloads. Add the tag and the reload starts working.
Related posts about platform: