@js0.site/x
v0.1.11
Published
Minimalist DOM utilities and smart TLD detection. / 极简 DOM 工具与智能 TLD 检测。
Downloads
838
Maintainers
Readme
X : Minimalist DOM Utilities & TLD Detection
X is a lightweight, zero-dependency JavaScript utility library designed to simplify DOM manipulation and provide accurate Top-Level Domain (TLD) detection. With a minimalist API, it helps developers build web applications quickly while avoiding heavy dependencies.
Key Features
- Simplified DOM Operations: Shorthand functions like
TagandOnreduce boilerplate code significantly. - Web Component Encapsulation: Simplify custom element definition and style loading with
CandSfunctions. - Smart TLD Detection: Dynamically identifies the effective top-level domain (eTLD+1) of the current page, leveraging browser Cookie security policies instead of maintaining a large suffix list.
- Dynamic Style Loading: Supports on-demand loading of CSS modules.
- HTML Escaping: Lightweight
HtmEfunction to safely escape HTML strings using native browser behavior, preventing XSS.
API List
src/_.js
DOM Shortcuts
DOC: Alias for thedocumentobject.BODY: Alias for thedocument.bodyobject.Tag(tagName): Bound function fordocument.createElementto quickly create DOM elements.Div(): Shortcut forTag('div'), creates a<div>element.
Components & Styles
C(name, class): Registers a Custom Element. Automatically prefixesnamewithi-(e.g.,btnbecomes<i-btn>).Style(name): Asynchronously loads a CSS module. Imports style from-/css/{name}.jsand injects it into<head>.S(name, class): Composite function. AwaitsStyle(name)loading, then callsC(name, class)to register the component.
Events & Utilities
On(element, events): Batch binds events to an element.- Params
events: Key-value object, e.g.,{ click: handler, mouseenter: handler }. - Returns: A void function that removes all event listeners bound in this call.
- Params
HtmE(text): HTML escaping utility. Uses browser native behavior to safely escape text into HTML entities.TEXTAREA: Reusable<textarea>element used internally byHtmE(exported).
src/TLD.js
default: (String) The current effective top-level domain (eTLD+1).
Usage Demo
DOM Manipulation & Event Binding
import { Tag, On, BODY } from "@js0.site/x/_.js";
// Create an element
const btn = Tag("button");
btn.textContent = "Click Me";
// Batch bind events (returns a cleanup function)
const off = On(btn, {
click: () => console.log("Clicked"),
mouseenter: () => console.log("Mouse entered")
});
BODY.appendChild(btn);
// Clean up events later
// off();Custom Elements & Styles
import { S } from "@js0.site/x/_.js";
// Load style and define component 'i-my-component'
await S("my-component", class extends HTMLElement {
constructor() {
super();
this.innerHTML = "<div>This is a custom component</div>";
}
});HTML Escaping
import { HtmE } from "@js0.site/x/_.js";
const safeHtml = HtmE("<script>alert('XSS')</script>");
console.log(safeHtml);
// Output: <script>alert('XSS')</script>Get Current TLD
import TLD from "@js0.site/x/TLD.js";
console.log("Current Effective TLD:", TLD);
// e.g., on www.google.co.uk, checks will verify and output 'google.co.uk'Design Philosophy
Module Workflow
- _.js (Core Library): Wraps native browser APIs (e.g.,
document.createElement,addEventListener). TheStylefunction decouples logic from styling by dynamically importing CSS JS modules from remote or aliased paths. - TLD.js (Domain Detection): Uses a Cookie Probing Method.
- The script splits the current hostname by
.. - Starting from the shortest suffix (e.g.,
com), it attempts to set a cookie. - Browser security policies prevent setting cookies on Public Suffixes (like
co.ukorcom), so these attempts fail. - Once a cookie is successfully set, that level is identified as the valid eTLD+1.
- This approach eliminates the need to bundle the 100KB+ Public Suffix List, keeping the library incredibly small.
- The script splits the current hostname by
Tech Stack
- Language: Vanilla JavaScript (ES2020+)
- Module System: Native ES Modules (ESM)
- Dependencies: Zero external dependencies
Directory Structure
.
├── src
│ ├── _.js # DOM operations, event management, custom element wrapper
│ └── TLD.js # Dynamic TLD detection algorithm
├── test
│ └── main.coffee # Test entry point
└── package.json # Project metadataHistorical Anecdote: Supercookies & The Public Suffix List
In the early days of the Web, browser scope restrictions for cookies were loose. You could set a cookie for .com, which led to the infamous "Supercookie" problem—unrelated companies (like google.com and amazon.com) shared the same .com cookie space, creating massive privacy and security vulnerabilities.
To solve this, Mozilla launched the Public Suffix List (PSL) project in 2005. It is a massive, manually maintained list of all suffixes that are "top-level" yet allow user registration (e.g., co.uk, github.io). Browser vendors embed this list to determine legitimate cookie boundaries.
However, the PSL file is large and updates frequently. TLD.js in this project takes a different path. Instead of relying on a static list, it leverages the PSL rules already enforced by the browser, using runtime "trial and error" to reverse-engineer the current valid TLD. This method pays homage to web security history while embodying the hacker spirit of minimalism.
About
This project is an open-source component of js0.site ⋅ Refactoring the Internet Plan.
We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:
X : 极简 Web 开发工具库
X 是一个轻量级、零依赖的 JavaScript 工具库,旨在简化 DOM 操作并提供精准的 TLD(顶级域名)检测功能。它通过极简的 API 设计,帮助开发者快速构建 Web 应用,同时摒弃了繁重的依赖包。
核心功能
- DOM 操作简化:提供
Tag、id、On等快捷函数,大幅减少样板代码。 - Web Component 封装:通过
C和S函数,简化自定义元素的定义与样式加载。 - 智能 TLD 检测:利用浏览器 Cookie 安全策略,动态识别当前页面的有效顶级域名(eTLD+1),无需维护庞大的后缀列表。
- 动态样式加载:支持按需加载 CSS 模块。
API 列表
src/_.js
DOM 快捷方式
DOC:document对象的别名。BODY:document.body对象的别名。Tag(tagName):document.createElement的绑定函数,用于快速创建 DOM 元素。Div():Tag('div')的快捷方式,创建一个<div>元素。
组件与样式
C(name, class): 注册自定义元素(Web Component)。会自动为name添加i-前缀(如btn变为<i-btn>)。Style(name): 异步加载 CSS 模块。它会从-/css/{name}.js导入样式并注入到<head>中。S(name, class): 组合函数。先等待Style(name)加载完成,再调用C(name, class)注册组件。
事件与工具
On(element, events): 为元素批量绑定事件。- 参数
events: 键值对对象,如{ click: handler, mouseenter: handler }。 - 返回值: 一个无参函数,调用即可移除所有在此次调用中绑定的事件监听器。
- 参数
HtmE(text): HTML 转义工具。利用浏览器的原生行为将文本安全地转义为 HTML 实体。TEXTAREA:HtmE内部使用的复用<textarea>元素(已导出)。
src/TLD.js
default: (String) 当前页面的有效顶级域名(eTLD+1)。
使用演示
DOM 操作与事件绑定
import { Tag, On, BODY } from "@js0.site/x/_.js";
// 创建元素
const btn = Tag("button");
btn.textContent = "点击我";
// 批量绑定事件(返回解绑函数)
const off = On(btn, {
click: () => console.log("被点击了"),
mouseenter: () => console.log("鼠标移入")
});
BODY.appendChild(btn);
// 清理事件
// off();自定义元素与样式
import { S } from "@js0.site/x/_.js";
// 加载样式并定义组件 i-my-component
await S("my-component", class extends HTMLElement {
constructor() {
super();
this.innerHTML = "<div>这是一个自定义组件</div>";
}
});获取当前 TLD
import TLD from "@js0.site/x/TLD.js";
console.log("当前有效主域名:", TLD);
// 例如在 www.google.co.uk 访问,将输出 google.co.uk设计思路
模块调用流程
- _.js (基础库):直接封装浏览器原生 API(如
document.createElement,addEventListener)。Style函数通过动态 import 加载远端或别名路径下的 CSS JS 模块,实现了逻辑与样式的解耦。 - TLD.js (域名检测):采用 Cookie 试探法。
- 脚本将当前域名按
.分割。 - 从最短后缀开始(如
com),尝试设置 Cookie。 - 由于浏览器安全策略禁止在 Public Suffix(如
co.uk或com)上设置 Cookie,操作会失败。 - 一旦 Cookie 设置成功,该层级即为有效的 eTLD+1。
- 此方法避免了内置几百 KB 的 Public Suffix List 数据,保持了库的极小体积。
- 脚本将当前域名按
技术堆栈
- 语言:Vanilla JavaScript (ES2020+)
- 模块规范:Native ES Modules (ESM)
- 依赖:无任何第三方依赖
目录结构
.
├── src
│ ├── _.js # DOM 操作、事件管理、自定义元素封装
│ └── TLD.js # 动态 TLD 检测算法
├── test
│ └── main.coffee # 测试入口
└── package.json # 项目元数据历史小故事:Supercookies 与 Public Suffix List
在 Web 的早期,浏览器对于 Cookie 的作用域限制较为宽松。你可以给 .com 设置 Cookie,这导致了著名的 "Supercookie" 问题——不同公司(如 google.com 和 amazon.com)竟然能共享同一个 .com 下的 Cookie,引发了严重的隐私和安全隐患。
为了解决这个问题,Mozilla 在 2005 年发起了 Public Suffix List (PSL) 项目。这是一个庞大的手工维护列表,记录了所有“即是顶级但又允许注册子域名”的后缀(例如 co.uk,github.io)。浏览器厂商通过内置这个列表来判断 Cookie 的合法边界。
然而,PSL 文件体积庞大且更新频繁。本项目中的 TLD.js 另辟蹊径,不依赖静态列表,而是利用浏览器已经遵循的 PSL 规则,通过运行时“试错”来反向推导当前的有效 TLD。这种方法既致敬了 Web 安全的历史,又体现了极客精神的轻量化追求。
关于
本项目为 js0.site ⋅ 重构互联网计划 的开源组件。
我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注:
