<!DOCTYPE html> <htmllang="en"> <head> <metacharset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <metaname="theme-color"content="#000000" /> <!-- manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ --> <linkrel="manifest"href="%PUBLIC_URL%/manifest.json" /> <linkrel="shortcut icon"href="%PUBLIC_URL%/favicon.ico" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript> You need to enable JavaScript to run this app. </noscript> <divid="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
不過如果打包過後,會把一些必要的資源給加上去。 特別是在 body 最底下,你會發現突然多出了一些 chunk script。 之所以打包軟體會把 script 放到最底下也是因為避免發生 render blocking 的狀況(後面會再提到) 而且不允許同時下載兩個 script: The HTTP specification defines that browsers should not download more than two components in parallel.
// my-script.js document.addEventListener("DOMContentLoaded", function () { // this function runs when the DOM is ready, i.e. when the document has been parsed document.getElementById("user-greeting").textContent = "Welcome back, Bart"; });
body
head 讀取完之後,再來就會開始讀取 body 內的 DOM。 root div 會先畫,再來解析後面的 script。
操作 DOM
因為畫面的結構已經在上方的 body 呈現了,所以如果想要設計 script 來操作 DOM 互動,就可以寫在下方。
CSS in JS
目前比較提倡 script 能盡量放 body 最下面就放那邊,你也會發現打包軟體或是前端的框架也是這樣做。 例如:emotion 的 styled-component 就是在要用到特定的 style 的時候,再把特定的 style 放到某個 DOM 之前。