How to add magic to the page
You can place code in several ways, but not all of them are equally good for your website's speed.
1. Internal and External Scripts
You can write code directly in HTML inside <script> tags, but for large projects, it's always better to put it in a separate .js file. This allows the browser to cache (save) the code so it doesn't have to download it every time.
2. The " White Screen " Problem
When the browser reads HTML and reaches <script src="...">, it stops. It drops everything and waits for the file to download and execute. Only then does it continue to paint the website.
3. The Solution: Async and Defer
For your site to load instantly, use these attributes:
- async (Asynchronous): " Download in the background and run IMMEDIATELY once downloaded " . The execution order of multiple scripts is not guaranteed (first to download is the first to run).
- defer (Deferred): " Download in the background and run ONLY when the entire site is painted " . The perfect choice for 99% of cases.
Mental model: A script with defer is a polite guest who waits for you to finish speaking. A script with async is an impatient friend who interrupts the conversation the moment they arrive.
If one script uses functions from another (e.g., a library and your code), use defer. It guarantees that the scripts will run in the correct order.