惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
V
V2EX
博客园_首页
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
H
Help Net Security
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
W
WeLiveSecurity
云风的 BLOG
云风的 BLOG
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
G
Google Developers Blog
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏
Hacker News: Ask HN
Hacker News: Ask HN
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
T
Troy Hunt's Blog
T
Tenable Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Recorded Future
Recorded Future
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog
T
Threat Research - Cisco Blogs
MyScale Blog
MyScale Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence

白云苍狗

LLM Agent 常用范式详解 - 白云苍狗的小站 利用 AI 编程提效体验 - 白云苍狗的小站 项目验收需要做哪些东西? - 白云苍狗的小站 vitepress 自定义主题教程 - 白云苍狗的小站 从 hexo 迁移到 Vitepress - 白云苍狗的小站 vitepress-theme-async 主题发布 - 白云苍狗的小站 自建免费 Moe-Counter 计数器 - 白云苍狗的小站 Hexo 主题开发之自定义模板 - 白云苍狗的小站 手撸 Grid 拖拽布局 - 白云苍狗的小站 前端基建之工具篇 - 白云苍狗的小站 uni-app 使用体验 - 白云苍狗的小站 hexo 在线编辑器 - 白云苍狗的小站 2023年,还在手动发布 npm 包? - 白云苍狗的小站 小程序 swiper 性能优化 - 白云苍狗的小站 瀑布流使用虚拟列表性能优化 - 白云苍狗的小站 做了个壁纸小程序😀 - 白云苍狗的小站 hexo-theme-async 使用指北 - 白云苍狗的小站 云开发又又又涨价了 - 白云苍狗的小站 关于重写评论插件这件事 - 白云苍狗的小站
Pjax 下动态加载插件方案 - 白云苍狗的小站
本文作者:白云苍狗 · 2022-09-28 · via 白云苍狗

距离上次更新已经 1265 天了, 文章内容可能已经过时。

在纯静态网站里,有时候会动态更新某个区域往会选择 Pjax(swup、barba.js)去处理,他们都是使用 ajax 和 pushState 通过真正的永久链接,页面标题和后退按钮提供快速浏览体验。

但是实际使用中可能会遇到不同页面可能会需要加载不同插件处理,有些人可能会全量选择加载,这样会导致加载很多无用的脚本,有可能在用户关闭页面时都不一定会访问到,会很浪费资源。

解决思路 ​

首先想到的肯定是在请求到新的页面后,我们手动去比较当前 DOM 和 新 DOM 之间 script 标签的差异,手动给他插入到 body 里。

处理 Script ​

一般来说 JavaScript 脚本都是放在 body 后,避免阻塞页面渲染,假设我们页面脚本也都是在 body 后,并在 script 添加 [data-reload-script] 表明哪些是需要动态加载的。

首先我们直接获取到带有 [data-reload-script] 属性的 script 标签:

js

// NewHTML 为 新页面 HTML
const pageContent = NewHTML.replace('<body', '<div id="DynamicPluginBody"').replace('</body>', '</div>');
let element = document.createElement('div');
element.innerHTML = pageContent;
const children = element.querySelector('#DynamicPluginBody').querySelectorAll('script[data-reload-script]');

然后通过创建 script 标签插入到 body

js

children.forEach(item => {
    const element = document.createElement('script');
    for (const { name, value } of arrayify(item.attributes)) {
        element.setAttribute(name, value);
    }
    element.textContent = item.textContent;
    element.setAttribute('async', 'false');
    document.body.insertBefore(element)
})

如果你的插件都是通过 script 引入,且不需要执行额外的 JavaScript 代码,只需要在 Pjax 钩子函数这样处理就可以了。

执行代码块 ​

实际很多插件不仅仅需要你引入,还需要你手动去初始化做一些操作的。我们可以通过 src 去判断是引入的脚本,还是代码块。

js

let scripts = Array.from(document.scripts)
let scriptCDN = []
let scriptBlock = []

children.forEach(item => {
    if (item.src)
        scripts.findIndex(s => s.src === item.src) < 0 && scriptCDN.push(item);
    else
        scriptBlock.push(item.innerText)
})

scriptCDN 继续通过上面方式插入到 body 里,然后通过 eval 或者 new Function 去执行 scriptBlock 。因为 scriptBlock 里的代码可能是会依赖 scriptCDN 里的插件的,所以需要在 scriptCDN 加载完成后在执行 scriptBlock 。

js

const loadScript = (item) => {
    return new Promise((resolve, reject) => {
        const element = document.createElement('script');
        for (const { name, value } of arrayify(item.attributes)) {
            element.setAttribute(name, value);
        }
        element.textContent = item.textContent;
        element.setAttribute('async', 'false');
        element.onload = resolve
        element.onerror = reject
        document.body.insertBefore(element)
    })
}

const runScriptBlock = (code) => {
    try {
        const func = new Function(code);
        func()
    } catch (error) {
        try {
            window.eval(code)
        } catch (error) {
        }
    }
}

Promise.all(scriptCDN.map(item => loadScript(item))).then(_ => {
    scriptBlock.forEach(code => {
        runScriptBlock(code)
    })
})

卸载插件 ​

按照上面思去处理之后,会存在一个问题。 比如:我们添加了一个 全局的 'resize' 事件的监听,在跳转其他页面时候我们需要移除这个监听事件。

这个时候我们需要对代码块的格式进行一个约束,比如像下面这样,在初次加载时执行 mount 里代码,页面卸载时执行 unmount 里代码。

js

<script data-reload-script>
    DynamicPlugin.add({
        // 页面加载时执行
        mount() {
            this.timer = setInterval(() => {
                document.getElementById('time').innerText = new Date().toString()
            }, 1000)
        },
        // 页面卸载时执行
        unmount() {
            window.clearInterval(this.timer)
            this.timer = null
        }
    })
</script>

DynamicPlugin 大致结构:

js

let cacheMount = []
let cacheUnMount = []
let context = {}

class DynamicPlugin {
    add(options) {
        if (isFunction(options))
            cacheMount.push(options)

        if (isPlainObject(options)) {
            let { mount, unmount } = options
            if (isFunction(mount))
                cacheMount.push(mount)
            if (isFunction(unmount))
                cacheUnMount.push(unmount)
        }

        // 执行当前页面加载钩子
        this.runMount()
    }

    runMount() {
        while (cacheMount.length) {
            let item = cacheMount.shift();
            item.call(context);
        }
    }

    runUnMount() {
        while (cacheUnMount.length) {
            let item = cacheUnMount.shift();
            item.call(context);
        }
    }
}

页面卸载时调用 DynamicPlugin.runUnMount()。

处理 Head ​

Head 部分处理来说相对比较简单,可以通过拿到新旧两个 Head,然后循环对比每个标签的 outerHTML,用来判断哪些比是需要新增的哪些是需要删除的。

结尾 ​

本文示例代码完整版本可以 参考这里