jQuery 安装
核对下载本地 jQuery(开发版/生产版)、HTML5 省略 script type 属性、国内与国际常见 CDN 引入方式,以及在控制台用 $.fn.jquery 检查版本。
学完这一章,你能够
- 核对下载本地 jQuery(开发版/生产版)、HTML5 省略 script type 属性、国内与国际常见 CDN 引入方式,以及在控制台用 $.fn.jquery 检查版本。
网页中添加 jQuery 与本地下载
在网页中引入 jQuery 主要有两种途径:一是从官网 `jquery.com` 下载脚本文件并随站点部署,二是通过公共 CDN(内容分发网络)直接远程引用。
官网提供两个构建版本:Production version(生产版,经过精简压缩,体积更小,适合线上站点)与 Development version(开发版,保留完整格式与注释,便于调试阅读)。将下载好的 `.js` 文件放入网页同目录或静态资源目录后,在 `<head>` 中通过 `<script src="jquery-1.10.2.min.js"></script>` 引用即可使用。在 HTML5 中无需再写 `type="text/javascript"`,因为 JavaScript 已是默认脚本语言。本站离线实测:省略 `type` 属性的 `<script>`(`getAttribute('type') === null`)在 Chromium 中正常加载并使 `$ === jQuery` 生效;对比可读开发版(`521` 字节)与去除注释空白后的精简生产版(`399` 字节),两者执行 `hide()` 均将目标元素设为 `display: none`。
通过 CDN 引用 jQuery 与选型权衡
若不希望自行托管脚本文件,可选用公共 CDN。面向中国大陆用户时通常优先选择百度、又拍云、Staticfile、新浪等国内可用节点,面向海外用户时可使用 CDNJS、Google 或 Microsoft CDN;实际站点也可统一接入自有静态资源库以降低第三方波动风险。以下汇总了常见的 6 种 CDN `<script>` 引用写法(本站离线实验仅在惰性 `<template>` 中解析核对这 7 条标签结构,不发起外网请求,确认本地相对路径与 6 条 HTTPS `.min.js` 地址均省略 `type` 属性)。
常见引用节点包括百度 CDN(`apps.bdimg.com`)、CDNJS(`cdnjs.cloudflare.com`)、又拍云 CDN(`upcdn.b0.upaiyun.com`)、Staticfile CDN(`cdn.staticfile.net`)、Google CDN(`ajax.googleapis.com`)与 Microsoft CDN(`ajax.aspnetcdn.com`)。需要注意 Google CDN 在中国大陆访问稳定性较差;同时部分历史示例中的 `1.x`/`2.x` 版本较旧,生产环境应选用最新维护版并配合 SRI(Subresource Integrity)或本地回退。
在浏览器控制台查看 jQuery 版本
排查页面冲突或确认已加载版本时,可打开浏览器开发者工具的 Console 控制台并执行 `$.fn.jquery`(或 `jQuery.fn.jquery`),返回值即为当前生效的版本号字符串。来源参考截图演示了在 Chrome DevTools Console 中输入 `$.fn.jquery` 后返回 `"1.3.2"`;本站离线 Chromium 实测读取 `$.fn.jquery` 与 `jQuery.fn.jquery` 均精确返回 `"3.7.1-offline-lab"`。
HTML5 脚本默认类型提示
| 提示主题 | 核心说明 |
|---|---|
| 为何省略 type="text/javascript"? | HTML5 及现代浏览器已将 JavaScript 设为 <script> 标签的默认脚本语言,直接书写 <script src="..."></script> 即可正常解析执行。 |
国内网络环境选型提示
| 提示主题 | 核心说明 |
|---|---|
| Google CDN 稳定性说明 | 面向中国大陆访客时不建议使用 Google CDN 加载 jQuery,因其网络连通性不稳定,易阻塞页面脚本初始化。 |
CDN 引入性能优势提示
| 提示主题 | 核心说明 |
|---|---|
| CDN 缓存命中与就近分发 | CDN 会从距访客较近的边缘节点返回文件,降低网络往返延迟;若访客访问其他站点时已加载过同一 CDN 路径(现代浏览器缓存分区策略下主要受惠于同站复用与边缘加速),还可进一步缩短加载耗时。 |
运行 HTML5 脚本默认类型、本地/CDN 引用结构与 $.fn.jquery 版本检查实验
"""Offline Playwright Chromium lab for jQuery Chapter 3 (install)."""
import json
import re
from playwright.sync_api import sync_playwright
DEV_HELPER = """
(function (global) {
// Development readable edition of offline mini-jQuery helper
function JQ(elements) {
this.elements = elements;
this.length = elements.length;
}
JQ.prototype.hide = function () {
this.elements.forEach(function (el) {
el.style.display = "none";
});
return this;
};
function $(selector) {
return new JQ(Array.from(document.querySelectorAll(selector)));
}
$.fn = JQ.prototype;
$.fn.jquery = "3.7.1-offline-lab";
global.$ = global.jQuery = $;
})(window);
""".strip()
PROD_HELPER = re.sub(r"//[^\n]*", "", DEV_HELPER)
PROD_HELPER = re.sub(r"\s+", " ", PROD_HELPER).replace(" ;", ";").replace("{ ", "{").replace(" }", "}").strip()
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery 安装离线实验</title>
<script id="inline-html5-script">{DEV_HELPER}</script>
<template id="script-ref-catalog">
<script data-kind="local" src="jquery-1.10.2.min.js"></script>
<script data-kind="baidu" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script data-kind="cdnjs" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script data-kind="upyun" src="https://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.2.min.js"></script>
<script data-kind="staticfile" src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
<script data-kind="google" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script data-kind="microsoft" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
</template>
</head>
<body>
<p id="demo-dev">开发版测试段落</p>
<p id="demo-prod">生产版测试段落</p>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as pw:
browser = launch_browser(pw)
try:
page = browser.new_page()
page.set_content(HTML_DOC, wait_until="load")
# Case 1: HTML5 <script> omits type="text/javascript" and executes by default
act1 = page.evaluate(
"""() => {
const s = document.getElementById("inline-html5-script");
return {
type_attr: s.getAttribute("type"),
dollar_type: typeof window.$,
alias_equal: window.$ === window.jQuery,
matched_p: $("p").length
};
}"""
)
exp1 = {
"type_attr": None,
"dollar_type": "function",
"alias_equal": True,
"matched_p": 2,
}
cases.append(dict(name="html5_script_default_js", passed=(act1 == exp1), expected=exp1, actual=act1))
# Case 2: Inspect local & 6 CDN <script src> declarations offline inside <template>
act2 = page.evaluate(
"""() => {
const tpl = document.getElementById("script-ref-catalog");
const items = Array.from(tpl.content.querySelectorAll("script")).map(el => ({
kind: el.dataset.kind,
has_type: el.hasAttribute("type"),
is_https: el.getAttribute("src").startsWith("https://"),
ends_min_js: el.getAttribute("src").endsWith(".min.js")
}));
return { count: items.length, items };
}"""
)
exp2 = {
"count": 7,
"items": [
{"kind": "local", "has_type": False, "is_https": False, "ends_min_js": True},
{"kind": "baidu", "has_type": False, "is_https": True, "ends_min_js": True},
{"kind": "cdnjs", "has_type": False, "is_https": True, "ends_min_js": True},
{"kind": "upyun", "has_type": False, "is_https": True, "ends_min_js": True},
{"kind": "staticfile", "has_type": False, "is_https": True, "ends_min_js": True},
{"kind": "google", "has_type": False, "is_https": True, "ends_min_js": True},
{"kind": "microsoft", "has_type": False, "is_https": True, "ends_min_js": True},
],
}
cases.append(dict(name="local_and_cdn_script_refs", passed=(act2 == exp2), expected=exp2, actual=act2))
# Case 3: Console $.fn.jquery version check
act3 = page.evaluate(
"""() => ({
fn_jquery: $.fn.jquery,
jquery_fn_jquery: jQuery.fn.jquery,
semver_prefix: $.fn.jquery.split("-")[0]
})"""
)
exp3 = {
"fn_jquery": "3.7.1-offline-lab",
"jquery_fn_jquery": "3.7.1-offline-lab",
"semver_prefix": "3.7.1",
}
cases.append(dict(name="console_fn_jquery_version", passed=(act3 == exp3), expected=exp3, actual=act3))
# Case 4: Development vs production (minified) script behavior & size
page2 = browser.new_page()
page2.set_content(
f"<!DOCTYPE html><html><head><script>{PROD_HELPER}</script></head><body><p id='t'>ok</p></body></html>",
wait_until="load",
)
dev_disp = page.evaluate("() => { $('#demo-dev').hide(); return getComputedStyle(document.getElementById('demo-dev')).display; }")
prod_disp = page2.evaluate("() => { $('#t').hide(); return getComputedStyle(document.getElementById('t')).display; }")
page2.close()
dev_bytes = len(DEV_HELPER.encode("utf-8"))
prod_bytes = len(PROD_HELPER.encode("utf-8"))
act4 = {
"dev_bytes": dev_bytes,
"prod_bytes": prod_bytes,
"prod_smaller": prod_bytes < dev_bytes,
"dev_display_after_hide": dev_disp,
"prod_display_after_hide": prod_disp,
}
exp4 = {
"dev_bytes": dev_bytes,
"prod_bytes": prod_bytes,
"prod_smaller": True,
"dev_display_after_hide": "none",
"prod_display_after_hide": "none",
}
cases.append(dict(name="production_vs_development_size", passed=(act4 == exp4), expected=exp4, actual=act4))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对无 type 属性 <script> 在 Chromium 正常执行、7 条本地与 CDN 脚本标签结构、$.fn.jquery 返回值,以及开发版(521B)与压缩版(399B)等效行为。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:c39b399d50fc4a5523d4104cd88ee15f99197fb020fbfce2a2f4a4078843539a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:76a740d6fc6cd0acb196960e955a7989ca134667a7104ab3757c1c79ff124416
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
下载 jQuery 时的 Production version 与 Development version 有何区别?如何在浏览器控制台确认当前页面加载的 jQuery 版本?
展开参考解答
Production version 经过压缩混淆体积小,适合线上部署;Development version 未压缩且可读,适合开发调试。在浏览器 Console 执行 $.fn.jquery(或 jQuery.fn.jquery)即可返回当前版本字符串。