
Security News
GitHub Actions Checkout Now Blocks Risky pull_request_target Checkouts
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.
一个轻量级的前端工具库,提供常用的工具函数和实用功能。
npm install dz-script
import { animate, delay, isObject, downloadFile } from 'dz-script';
// 使用动画函数
animate(0, 100, (value) => {
console.log(value);
}, 1000);
// 延迟执行
await delay(2000);
// 类型检查
console.log(isObject({})); // true
// 文件下载
downloadFile('https://example.com/file.pdf', 'document.pdf');
<script src="https://unpkg.com/dz-script/dist/dz-script.js"></script>
<script>
// 通过全局变量 dzUtils 访问
dzUtils.animate(0, 100, (value) => {
console.log(value);
}, 1000);
</script>
setLocal: 设置本地存储getLocal: 获取本地存储removeLocal: 删除本地存储clearLocal: 清空本地存储setSession: 设置会话存储getSession: 获取会话存储removeSession: 删除会话存储clearSession: 清空会话存储数字动画函数,使用 requestAnimationFrame 实现平滑动画。
import { animate } from 'dz-script';
// 从0到100的动画,持续1秒
animate(0, 100, (value) => {
element.style.width = value + 'px';
}, 1000);
参数:
from (number): 起始值to (number): 结束值callback (function): 回调函数,接收当前动画值duration (number): 动画持续时间(毫秒)异步延迟函数。
import { delay } from 'dz-script';
// 延迟2秒
await delay(2000);
console.log('2秒后执行');
深度合并对象。
import { deepMerge } from 'dz-script';
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const result = deepMerge(obj1, obj2);
// 结果: { a: 1, b: { c: 2, d: 3 }, e: 4 }
文件下载工具。
import { downloadFile } from 'dz-script';
downloadFile('https://example.com/file.pdf', 'document.pdf');
将对象序列化为查询字符串。
import { serialize } from 'dz-script';
const params = { name: 'John', age: 30 };
const queryString = serialize(params);
// 结果: "name=John&age=30"
数组分组函数。
import { groupBy } from 'dz-script';
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 30 }
];
// 按年龄分组
const grouped = groupBy(users, 'age');
// 结果: { 25: [{ name: 'John', age: 25 }, { name: 'Jane', age: 25 }], 30: [{ name: 'Bob', age: 30 }] }
// 按自定义函数分组
const groupedByLength = groupBy(users, (user) => user.name.length);
import { setLocal, getLocal, removeLocal, clearLocal } from 'dz-script';
import { setSession, getSession, removeSession, clearSession } from 'dz-script';
// LocalStorage 操作
setLocal('user', { name: 'John' });
const user = getLocal('user');
removeLocal('user');
clearLocal();
// SessionStorage 操作
setSession('token', 'abc123');
const token = getSession('token');
removeSession('token');
clearSession();
文件上传Hook。
import { useUploadFile } from 'dz-script';
const { uploadFun, clear } = useUploadFile(
(file) => {
console.log('选择的文件:', file);
// 处理文件上传逻辑
},
(error) => {
console.error('上传错误:', error);
}
);
// 触发文件选择
uploadFun();
// 清理上传元素
clear();
页面自动重载功能,基于Web Worker实现,用于检测页面资源更新并自动重载。
import { updateWorkerjs } from 'dz-script';
const worker = new updateWorkerjs({
pollingTime: 15, // 轮询间隔(秒)
path: window.location.origin, // 页面路径
scriptUrl: 'https://example.com/reload.js' // Worker脚本地址
});
worker.on('update', () => {
console.log('检测到更新,准备重载页面');
location.reload();
});
worker.on('close', () => {
console.log('Worker已关闭');
});
// 关闭Worker
worker.close();
pollingTime (number): 轮询间隔时间,默认15秒path (string): 要监控的页面路径,默认为当前页面scriptUrl (string): Worker脚本地址,默认为远程地址初始化阶段:
监控阶段:
更新阶段:
updateWorkerjs 类:
class updateWorkerjs {
pollingTime: number; // 轮询间隔时间
private myWork: any; // Web Worker实例
path: string; // 监控的页面路径
private eventMap: any; // 事件映射表
scriptUrl: string; // Worker脚本地址
}
HTML解析器:
export type htmlObjType = {
nodeName: string;
text?: string;
src?: string;
children: htmlObjType[];
};
第一阶段:初始化
async createWorkerjs() {
// 1. 获取当前页面HTML
const htmlObj = await this._getHtmlObj();
// 2. 提取script标签的src作为版本标识
const currentHash = this._getCurrentHash(htmlObj);
// 3. 创建Web Worker
if (window.Worker) {
const workjsTemplate = await this._getScript();
const localWorkerUrl = window.URL.createObjectURL(
new Blob([workjsTemplate], {
type: 'application/javascript',
})
);
this.myWork = new Worker(localWorkerUrl);
// 4. 向Worker发送初始配置
this.myWork.postMessage({
pollingTime: this.pollingTime,
location: this.path || window.location.origin,
currentHash,
});
}
}
第二阶段:HTML获取与解析
async _getHtmlObj(): Promise<htmlObjType> {
const res = await fetch(window.location.origin, {
method: 'GET',
});
const data = await res.text();
return htmlTransform(data);
}
第三阶段:版本标识提取
_getCurrentHash(htmlObj: htmlObjType): string {
for (const child of htmlObj.children) {
if (child?.nodeName === 'script' && child?.src) {
return child.src; // 返回第一个script标签的src
}
// 递归查找子节点
const result = this._getCurrentHash(child);
if (result !== null) {
return result;
}
}
return null;
}
第四阶段:事件处理
this.myWork.onmessage = async (e: any) => {
const message = e.data;
if (message === 'update') {
this.emit('update'); // 触发更新事件
this.close(); // 关闭Worker
} else if (message === 'cancel') {
this._error('do not find a script tag');
this.close();
}
};
事件类型:
update: 检测到更新时触发close: Worker关闭时触发事件注册:
on(event: string, handler: (e: any) => void) {
this.eventMap.get(event).add(handler);
}
事件触发:
emit(event: string) {
this.eventMap.get(event).forEach((handler: Function) => {
handler(this, this);
});
}
优势:
限制:
npm install
# 构建库文件
npm run build
# 监听模式构建
npm run watch:bundle
npm run watch:lib
npm test
npm run lint
MIT License - 查看 LICENSE 文件了解详情。
欢迎提交 Issue 和 Pull Request!
FAQs
frontend tools
The npm package dz-script receives a total of 21 weekly downloads. As such, dz-script popularity was classified as not popular.
We found that dz-script demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.

Product
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.