"""Offline Playwright Chromium lab for jQuery Chapter 29 (noconflict)."""
import json
from playwright.sync_api import sync_playwright
BASE_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery noConflict() Lab</title></head>
<body>
<p id="p1">初始段落</p>
<button id="btn1" type="button">触发更新</button>
<script>
// 模拟页面中先加载的其他使用 $ 的框架(如 MooTools / Prototype)
window.$ = function otherFramework(name) {
return "OTHER_LIB:" + name;
};
window.jQuery = function priorJQuery() {
return "PRIOR_JQ";
};
// 模拟随后加载的离线 jQuery,保存既有引用并提供 noConflict(deep)
(function (global) {
const _$ = global.$;
const _jQuery = global.jQuery;
function wrap(nodes) {
const list = Array.from(nodes);
return {
click(fn) {
for (const el of list) el.addEventListener("click", fn);
return this;
},
text(val) {
if (val === undefined) return list.length ? list[0].textContent : "";
for (const el of list) el.textContent = val;
return this;
}
};
}
function jQuery(arg) {
if (arg === document) {
return {
ready(fn) {
fn(jQuery);
}
};
}
if (typeof arg === "string") return wrap(document.querySelectorAll(arg));
return wrap([]);
}
jQuery.noConflict = function (deep) {
if (global.$ === jQuery) {
global.$ = _$;
}
if (deep && global.jQuery === jQuery) {
global.jQuery = _jQuery;
}
return jQuery;
};
global.jQuery = global.$ = jQuery;
})(window);
</script>
</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 p:
browser = launch_browser(p)
try:
# Case 1: $.noConflict() + full name jQuery
page = browser.new_page(viewport={"width": 900, "height": 600})
page.set_content(BASE_HTML)
pre = page.evaluate("() => window.$ === window.jQuery")
page.evaluate("""() => {
$.noConflict();
jQuery(document).ready(function () {
jQuery("button").click(function () {
jQuery("p").text("jQuery 仍然在工作!");
});
});
}""")
page.click("#btn1")
c1 = page.evaluate("""() => ({
dollar_was_jquery_before: true,
dollar_after_is_other: window.$("demo"),
p_text_after_click: document.getElementById("p1").textContent,
jquery_still_global: typeof window.jQuery === "function"
})""")
c1["dollar_was_jquery_before"] = pre
exp1 = {
"dollar_was_jquery_before": True,
"dollar_after_is_other": "OTHER_LIB:demo",
"p_text_after_click": "jQuery 仍然在工作!",
"jquery_still_global": True,
}
cases.append({"name": "noconflict_releases_dollar_use_full_name", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: var jq = $.noConflict()
page.set_content(BASE_HTML)
page.evaluate("""() => {
var jq = $.noConflict();
window.__jqRef = jq;
jq(document).ready(function () {
jq("button").click(function () {
jq("p").text("自定义简写 jq 正常工作!");
});
});
}""")
page.click("#btn1")
c2 = page.evaluate("""() => ({
dollar_restored: window.$("alias"),
jq_equals_jquery: window.__jqRef === window.jQuery,
p_text_after_click: document.getElementById("p1").textContent
})""")
exp2 = {
"dollar_restored": "OTHER_LIB:alias",
"jq_equals_jquery": True,
"p_text_after_click": "自定义简写 jq 正常工作!",
}
cases.append({"name": "noconflict_custom_alias_jq", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: $.noConflict() + jQuery(document).ready(function($){ ... })
page.set_content(BASE_HTML)
page.evaluate("""() => {
$.noConflict();
window.__insideEqualsJQuery = false;
jQuery(document).ready(function ($) {
window.__insideEqualsJQuery = ($ === window.jQuery);
$("button").click(function () {
$("p").text("ready 局部参数 $ 生效!");
});
});
}""")
page.click("#btn1")
c3 = page.evaluate("""() => ({
inside_ready_dollar_is_jquery: window.__insideEqualsJQuery,
outside_global_dollar_is_other: window.$("outside"),
p_text_after_click: document.getElementById("p1").textContent
})""")
exp3 = {
"inside_ready_dollar_is_jquery": True,
"outside_global_dollar_is_other": "OTHER_LIB:outside",
"p_text_after_click": "ready 局部参数 $ 生效!",
}
cases.append({"name": "noconflict_ready_scoped_dollar", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: jQuery.noConflict(true) releases both $ and jQuery
page.set_content(BASE_HTML)
page.evaluate("""() => {
const isolated = jQuery.noConflict(true);
window.__isolatedText = isolated("p").text("深度释放后隔离实例仍可用").text();
}""")
c4 = page.evaluate("""() => ({
dollar_restored: window.$("deep"),
jquery_restored_to_prior: window.jQuery(),
isolated_text: window.__isolatedText
})""")
exp4 = {
"dollar_restored": "OTHER_LIB:deep",
"jquery_restored_to_prior": "PRIOR_JQ",
"isolated_text": "深度释放后隔离实例仍可用",
}
cases.append({"name": "noconflict_deep_true_releases_both", "passed": c4 == exp4, "expected": exp4, "actual": c4})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jquery-noconflict-lab/explore-noconflict.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-noconflict.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a897.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip