蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 实测 jQuery 单行/多行链式调用与查询次数对比

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-chaining.py
explore-chaining.py260 行
"""Offline Playwright Chromium lab for jQuery Chapter 13 (chaining)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <style>
    p { height: 40px; margin: 0; overflow: hidden; }
    .accent { font-weight: bold; }
  </style>
</head>
<body>
  <p id="p1">jQuery 方法链接演示段落</p>
  <p id="p2">多行缩进链式调用演示段落</p>
  <script>
    (function () {
      const queues = new WeakMap();
      const activeTimers = new Set();
      window.__queryCount = 0;
      window.__trace = [];

      function getQueue(el) {
        if (!queues.has(el)) queues.set(el, { active: null, pending: [] });
        return queues.get(el);
      }

      function startNext(el) {
        const q = getQueue(el);
        if (q.active || q.pending.length === 0) return;
        const job = q.pending.shift();
        if (job.onStart) job.onStart();
        q.active = { el, duration: job.duration, elapsed: 0, startH: job.startH, endH: job.endH, onDone: job.onDone };
        activeTimers.add(q.active);
      }

      window.__advance = function (ms) {
        for (const anim of Array.from(activeTimers)) {
          if (!activeTimers.has(anim)) continue;
          anim.elapsed += ms;
          const ratio = Math.min(1, anim.elapsed / anim.duration);
          const curH = anim.startH + (anim.endH - anim.startH) * ratio;
          anim.el.style.height = curH + 'px';
          if (anim.elapsed >= anim.duration) {
            activeTimers.delete(anim);
            const q = getQueue(anim.el);
            if (q.active === anim) q.active = null;
            if (anim.onDone) anim.onDone();
            startNext(anim.el);
          }
        }
      };

      function JQ(els) {
        this.els = Array.from(els);
        this.length = this.els.length;
      }

      JQ.prototype.css = function (prop, val) {
        if (val === undefined) {
          return this.els[0] ? getComputedStyle(this.els[0]).getPropertyValue(prop) : undefined;
        }
        this.els.forEach((el) => {
          el.style.setProperty(prop, val);
          window.__trace.push('css:' + prop + '=' + val);
        });
        return this;
      };

      JQ.prototype.addClass = function (cls) {
        this.els.forEach((el) => el.classList.add(cls));
        return this;
      };

      JQ.prototype.attr = function (name, val) {
        if (val === undefined) return this.els[0] ? this.els[0].getAttribute(name) : undefined;
        this.els.forEach((el) => el.setAttribute(name, val));
        return this;
      };

      JQ.prototype.text = function (val) {
        if (val === undefined) return this.els.map((e) => e.textContent).join('');
        this.els.forEach((el) => { el.textContent = val; });
        return this;
      };

      JQ.prototype.slideUp = function (duration) {
        this.els.forEach((el) => {
          getQueue(el).pending.push({
            duration,
            startH: 40,
            endH: 0,
            onDone: () => {
              el.style.display = 'none';
              window.__slideUpDisplay = getComputedStyle(el).display;
              window.__trace.push('slideUp:done');
            },
          });
          startNext(el);
        });
        return this;
      };

      JQ.prototype.slideDown = function (duration) {
        this.els.forEach((el) => {
          getQueue(el).pending.push({
            duration,
            startH: 0,
            endH: 40,
            onStart: () => {
              el.style.display = 'block';
              el.style.height = '0px';
            },
            onDone: () => {
              window.__trace.push('slideDown:done');
            },
          });
          startNext(el);
        });
        return this;
      };

      window.$ = function (sel) {
        window.__queryCount += 1;
        return new JQ(document.querySelectorAll(sel));
      };
    })();
  </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)
        page = browser.new_page(viewport={"width": 1000, "height": 700})
        page.set_content(HTML_DOC, wait_until="load")

        # Case 1: single-line css().slideUp(2000).slideDown(2000)
        c1 = page.evaluate("""() => {
            window.__queryCount = 0;
            window.__trace = [];
            window.__slideUpDisplay = null;
            $("#p1").css("color","red").slideUp(2000).slideDown(2000);
            const afterCssColor = getComputedStyle(document.querySelector('#p1')).color;
            window.__advance(2000);
            const afterUpDisplay = window.__slideUpDisplay;
            const handoffHeight = getComputedStyle(document.querySelector('#p1')).height;
            window.__advance(2000);
            const finalCs = getComputedStyle(document.querySelector('#p1'));
            return {
                queryCount: window.__queryCount,
                afterCssColor,
                afterUpDisplay,
                handoffHeight,
                finalDisplay: finalCs.display,
                finalHeight: finalCs.height,
                finalColor: finalCs.color,
                trace: window.__trace
            };
        }""")
        exp1 = {
            "queryCount": 1,
            "afterCssColor": "rgb(255, 0, 0)",
            "afterUpDisplay": "none",
            "handoffHeight": "0px",
            "finalDisplay": "block",
            "finalHeight": "40px",
            "finalColor": "rgb(255, 0, 0)",
            "trace": ["css:color=red", "slideUp:done", "slideDown:done"],
        }
        cases.append(dict(name="single_line_css_slideup_slidedown", expected=exp1, actual=c1, passed=c1 == exp1))

        # Case 2: multiline indented chain produces identical DOM & queue result
        c2 = page.evaluate("""() => {
            window.__queryCount = 0;
            window.__trace = [];
            window.__slideUpDisplay = null;
            $("#p2").css("color","red")
              .slideUp(2000)
              .slideDown(2000);
            window.__advance(2000);
            const midDisplay = window.__slideUpDisplay;
            window.__advance(2000);
            const cs = getComputedStyle(document.querySelector('#p2'));
            return {
                queryCount: window.__queryCount,
                midDisplay,
                finalDisplay: cs.display,
                finalColor: cs.color,
                trace: window.__trace
            };
        }""")
        exp2 = {
            "queryCount": 1,
            "midDisplay": "none",
            "finalDisplay": "block",
            "finalColor": "rgb(255, 0, 0)",
            "trace": ["css:color=red", "slideUp:done", "slideDown:done"],
        }
        cases.append(dict(name="multiline_indented_chain_equivalent", expected=exp2, actual=c2, passed=c2 == exp2))

        # Case 3: chaining performs 1 selector lookup vs 3 separate statements
        c3 = page.evaluate("""() => {
            window.__queryCount = 0;
            const w0 = $("#p1");
            const w1 = w0.css("color", "blue").addClass("accent").attr("data-chained", "yes");
            const chainedQueries = window.__queryCount;

            window.__queryCount = 0;
            $("#p2").css("color", "blue");
            $("#p2").addClass("accent");
            $("#p2").attr("data-chained", "yes");
            const separateQueries = window.__queryCount;
            return {
                chainedQueries,
                separateQueries,
                sameWrapper: w0 === w1,
                attrMatch: document.querySelector('#p1').getAttribute('data-chained') === 'yes'
            };
        }""")
        exp3 = {"chainedQueries": 1, "separateQueries": 3, "sameWrapper": True, "attrMatch": True}
        cases.append(dict(name="chaining_vs_separate_selector_lookups", expected=exp3, actual=c3, passed=c3 == exp3))

        # Case 4: getter returns value and terminates chain, setter returns jQuery wrapper
        c4 = page.evaluate("""() => {
            const colorVal = $("#p1").css("color");
            const textVal = $("#p1").text();
            return {
                colorVal,
                colorType: typeof colorVal,
                hasSlideUpOnGetter: typeof colorVal.slideUp === 'function',
                textVal
            };
        }""")
        exp4 = {
            "colorVal": "rgb(0, 0, 255)",
            "colorType": "string",
            "hasSlideUpOnGetter": False,
            "textVal": "jQuery 方法链接演示段落",
        }
        cases.append(dict(name="getter_breaks_chain_rule", expected=exp4, actual=c4, passed=c4 == exp4))

        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-chaining-lab/explore-chaining.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-chaining.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a881.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习