在 HTML 頁面的頭部包含指令碼標記
要從官方 CDN 載入 jQuery ,請轉到 jQuery 網站 。你將看到可用的不同版本和格式的列表。
https://i.stack.imgur.com/eOt5z.jpg
現在,複製你要載入的 jQuery 版本的原始碼。假設,你想載入 jQuery 2.X ,點選未壓縮或縮小的標籤,它會顯示如下:
https://i.stack.imgur.com/E8zjB.jpg
複製完整程式碼(或單擊複製圖示)並將其貼上到 html 的 <head>
或 <body>
中。
最佳實踐是使用 async
屬性在 head 標記處載入任何外部 JavaScript 庫。這是一個演示:
<!DOCTYPE html>
<html>
<head>
<title>Loading jquery-2.2.4</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" async></script>
</head>
<body>
<p>This page is loaded with jquery.</p>
</body>
</html>
當使用 async
屬性時,有意識的是,javascript 庫然後被非同步載入並儘快執行。如果包含兩個庫,其中第二個庫依賴於第一個庫,則如果第二個庫在第一個庫之前載入並執行,那麼它可能會丟擲錯誤並且應用程式可能會中斷。