"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jquery-install-lab/explore-install.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-install.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a894.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip