今日已更新 240 条资讯 | 累计 23823 条内容
关于我们

标签:#javascript

找到 648 篇相关文章

开源项目

🔥 huangxd- / danmu_api - 一个人人都能部署的基于 js 的弹幕 API 服务器,支持爱优腾芒哔咪人韩巴狐乐西埋帆弹幕直接获取,兼容弹弹play的搜

GitHub热门项目 | 一个人人都能部署的基于 js 的弹幕 API 服务器,支持爱优腾芒哔咪人韩巴狐乐西埋帆弹幕直接获取,兼容弹弹play的搜索、详情查询和弹幕获取接口规范,并提供日志记录,支持vercel/netlify/edgeone/cloudflare/docker/hf等部署方式,不用提前下载弹幕,没有nas或小鸡也能一键部署。 | Stars: 2,789 | 13 stars today | 语言: JavaScript

2026-07-20 原文 →
AI 资讯

Understanding Callback Functions in JavaScript

Introduction A callback function is one of the most important concepts in JavaScript. It allows one function to execute another function after completing a task. Callback functions are widely used in JavaScript for handling asynchronous operations such as API requests, file reading, event handling, and timers. What is a Callback Function? A callback function is a function that is passed as an argument to another function and is executed later. In simple words: A callback is a function that is called after another function finishes its work. Syntax function greeting () { console . log ( " Good Morning! " ); } function welcome ( callback ) { console . log ( " Welcome! " ); callback (); } welcome ( greeting ); Output Welcome! Good Morning! Explanation greeting() is the callback function. welcome() accepts a function as a parameter. callback() executes the greeting function after printing "Welcome!". Real-Life Example Imagine you order food at a restaurant. You place the order. The chef prepares the food. After the food is ready, the waiter serves it. Here, serving the food happens only after preparation is complete. This is exactly how callback functions work. Example 1: Email Sending function emailSent () { console . log ( " Email Sent Successfully! " ); } function sendEmail ( callback ) { console . log ( " Sending Email... " ); callback (); } sendEmail ( emailSent ); Output Sending Email... Email Sent Successfully! Example 2: Download File function downloadComplete () { console . log ( " Download Complete! " ); } function downloadFile ( callback ) { console . log ( " Downloading File... " ); callback (); } downloadFile ( downloadComplete ); Output Downloading File... Download Complete! Why Do We Use Callback Functions? Callback functions are useful because they: Execute code only after another task finishes. Improve code reusability. Handle asynchronous operations. Make event handling easier. Help avoid repeating code. Where Are Callback Functions Used? Some common u

2026-07-20 原文 →
AI 资讯

Just shipped @modyra/core: a tiny state layer for complex frontends

I've just published a small npm package called @modyra/core that came out of a very specific pain: handling "slightly complex" app state in frontend projects without ending up with a mess of context, custom hooks and scattered stores. The focus of the package is: Minimal API, all in TypeScript, no hidden magic No heavy runtime: just tools to model the core of your app as a set of state modules Designed to plug into React/Angular/vanilla JS without forcing you to rewrite everything The idea is to treat your app's domain as a set of "core units" with clear responsibilities: each unit exposes state, actions and rules, and the rest of the app simply consumes them. It came out of a few projects where Redux/Zustand/signals etc. were fine, but started to feel either too verbose or not very close to the actual business domain. If you feel like taking a look and tearing it apart, feedback (including harsh ones) is very welcome: naming, API design, examples - everything is still fresh enough to change. And if you think the approach is worth exploring, a star on GitHub would really help me keep pushing the project forward.

2026-07-20 原文 →
AI 资讯

Stop writing a parser per site. Run five and let confidence decide.

For a long time I ran product extraction off a database of custom selector configs. Hundreds of retailers, each with its own set of CSS selectors mapped field by field: price here, title there, image over there. It worked. It was also a treadmill. Every retailer that redesigned its frontend silently broke its config, and the maintenance tax grew with every retailer I added. Hundreds of configs is hundreds of things that can rot without telling you, usually right before someone downstream asks why a brand's prices went null. At some point I stopped feeding it. The scraping platform I ran at my last engagement fed a 20M+ product catalogue at millions of pages a day, and the thing that made that survivable wasn't better per-site config. It was leaning on almost no per-site config at all. The pattern Instead of one careful parser per site, run several cheap generic extractors on every page, in parallel: JSON-LD. A huge share of e-commerce pages ship a schema.org/Product block because Google rewards it. It has name, price, currency, availability, images. It's the closest thing to a public API hiding in the HTML. OpenGraph tags. og:title , og:image , product:price:amount . Lower quality than JSON-LD, but present on sites too lazy for structured data, because everyone wants pretty link previews. Microdata / RDFa. Older sites, still surprisingly common outside the US. Embedded state. __NEXT_DATA__ , window.__INITIAL_STATE__ and friends. A JSON blob the site's own frontend hydrates from. Heuristics. A price-shaped string near a currency symbol inside the main content region. The largest above-the-fold image. The h1 . Dumb, and dumb works more often than you'd think. None of these is reliable alone. OG price tags go stale, JSON-LD sometimes describes the wrong variant, heuristics grab the crossed-out "was" price. The trick is you don't pick an extractor. You pick per field, and you let agreement between sources carry the decision. Confidence merge Each extractor emits candida

2026-07-20 原文 →
AI 资讯

Installing traceless-style: A Step-by-Step Guide

Installation traceless-style is published to npm. It has no required dependencies at runtime and one optional dependency ( @swc/core ) that the SWC-backed extractor uses for large codebases. 1. Install the package npm install traceless-style # or pnpm add traceless-style # or yarn add traceless-style The package ships pre-built. There is no postinstall step. Peer dependency Required? What for react ≥ 18 Optional Only needed for the React components in traceless-style/dark and traceless-style/rtl ( <TracelessRoot /> , <ThemeToggle /> , <RtlToggle /> ). next ≥ 14 Optional Only needed if you use traceless-style/nextjs . webpack ≥ 5 Optional Only needed if you wire up the raw webpack plugin. vite Optional Only needed for traceless-style/vite . @swc/core Optional Auto-loaded for projects ≥ 100 source files. Falls back to the legacy parser if installation failed. 2. Pick an integration You're using… Install one of Next.js (App Router or Pages) traceless-style/nextjs Webpack directly (CRA-style or Rspack) traceless-style/webpack Vite traceless-style/vite Rollup traceless-style/rollup esbuild traceless-style/esbuild Just Node + a build script The CLI: npx traceless-style Each integration page contains a copy-paste config snippet. 3. Run init (recommended) npx traceless-style init This zero-config scaffolder: Detects your framework (Next, Vite, Remix, Astro). Adds the bundler plugin to your config file. Adds <TracelessRoot /> to your root layout (anti-flash dark + RTL script). Creates traceless-style.config.js if missing. Adds dev / build scripts to package.json if missing. Suggests installing the VS Code extension via .vscode/extensions.json . The scaffolder is idempotent — re-running it will not duplicate edits. 4. Verify the install Create a tiny component: // app/test-install.tsx import { tl } from " traceless-style " ; const $ = tl . create ({ hello : { color : " tomato " , padding : " 1rem " , fontSize : " 1.25rem " }, }); export default function Test () { return < div

2026-07-20 原文 →
开发者

MDN исходный код всего Web.

Я заглянул туда. Там дохуя документации. Дикий геморой мусорки. Бесконечный склад, который вгоняет меня в панику. Но как инструмент это незаменимая часть Web. Я беру нужный мне чертёж и строю то, что мне нужно. window глобальный объект. Подключение к API старого браузера. Это Мозг, который даёт мне инструменты: Скелет HTML: (document) Память Хранилище: (localStorage) Сеть API: подключение к контрактам других серверов для сбора информации (fetch) Но главное, что я заценил это обработчик событий onload. Это и есть чудо архитектуры. Связь CSS, JS, HTML в корневой папке предка HTML. Я скидываю в него свой модуль, и он гарантирует, что всё запустится, когда скелет будет готов.

2026-07-20 原文 →
AI 资讯

How the V8 Engine Optimizes JavaScript at Runtime

.The V8 engine speeds up JavaScript by dynamically compiling frequently run bytecode into optimized native machine code. However, if you pass inconsistent argument types to these optimized functions, V8 panics and deoptimizes back to bytecode. Keeping your functions monomorphic (single-typed) prevents this costly deoptimization loop, ensuring maximum runtime execution speed. If you’ve spent as much time digging into V8 execution flags as I have, you quickly realize that JavaScript is constantly rewriting itself under the hood. We like to think of JavaScript as a dynamically typed scripting language. But at runtime, engines like V8 are working tirelessly to turn your code into a highly optimized, statically typed powerhouse. When we violate that type stability, we pay a massive performance tax. How does the V8 engine optimize JavaScript at runtime? V8 uses a multi-tiered compilation pipeline that starts with an interpreter for fast startup times, then upgrades hot functions to optimized machine code using a JIT compiler. By tracking runtime type patterns, the engine can safely make assumptions to skip expensive dynamic lookups. When I look at V8’s execution pipeline, I see two primary systems working in tandem: Ignition (the interpreter) and TurboFan (the JIT compiler). Initially, Ignition compiles your raw JavaScript into bytecode so your app can boot instantly. As this bytecode executes, V8 allocates a data structure called a Feedback Vector for each function. Inside this vector are Feedback Slots (managed by Inline Caches, or ICs). These slots act as recorders, capturing the exact types (or "shapes") of the variables passing through your code. Once a function runs frequently enough to cross an execution threshold, V8 marks it as "hot" and hands it to TurboFan. TurboFan reads those feedback slots, assumes the types will remain identical in the future, and compiles a highly streamlined, native machine code version of that function. What happens when you pass differe

2026-07-20 原文 →
AI 资讯

Building Zero-Reload Web Forms: Master Modern Async/Await JavaScript Fetch API

Modern web applications demand responsive, non-blocking user flows. This tutorial demonstrates a production-grade implementation for handling form submissions without full-page reloads using the native Fetch API and clean async/await syntax. The Complete Source Code Create a file named app.js and drop in the following event-driven architecture: JavaScript document.getElementById('registrationForm').addEventListener('submit', async (event) => { event.preventDefault(); // 1. Stop full page reload const form = event.target; const formData = new FormData(form); const submitBtn = form.querySelector('button[type="submit"]'); const responseMessage = document.getElementById('responseMessage'); // 2. UI Feedback: Disable button during network request submitBtn.disabled = true; submitBtn.textContent = 'Processing...'; responseMessage.textContent = ''; try { // 3. Asynchronous Fetch Request const response = await fetch(form.action, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } }); // 4. Status Code Validation if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const result = await response.json(); // 5. Dynamic UI State Handling if (result.success) { responseMessage.style.color = '#155724'; responseMessage.textContent = result.message; form.reset(); // Clear form on success } else { responseMessage.style.color = '#721c24'; responseMessage.textContent = result.error || 'Submission failed.'; } } catch (error) { // 6. Global Error Catching responseMessage.style.color = '#721c24'; responseMessage.textContent = 'A network error occurred. Please try again.'; console.error('Submission tracking error:', error); } finally { // 7. Reset UI State Guaranteed submitBtn.disabled = false; submitBtn.textContent = 'Submit Data Securely'; } }); The Problem with Synchronous Form Lifecycles Traditional submissions trigger a synchronous navigation cycle: the browser constructs a payload, issues a full HTTP request, and replaces the

2026-07-20 原文 →
AI 资讯

TypeScript Generic Constraints in Depth: `extends`, `keyof`, and the Patterns That Prevent Runtime Errors

TypeScript Generic Constraints in Depth: extends , keyof , and the Patterns That Prevent Runtime Errors This article was written with the assistance of AI, under human supervision and review. Most TypeScript runtime errors stem from unconstrained generics that accept anything and crash on nothing. Teams write function get<T>(obj: T, key: string) and ship code that compiles cleanly but throws Cannot read property 'undefined' of undefined in production. The compiler stays silent because the generic accepts any type and the key accepts any string—no constraint exists to prove the key belongs to the object. Generic constraints solve this by restricting what types a generic parameter can accept. The extends keyword establishes a boundary—the generic must satisfy a specific shape. The keyof operator extracts valid keys from that shape. Together they form a type-level contract that makes illegal property access unrepresentable. The corrected signature function get<T, K extends keyof T>(obj: T, key: K): T[K] proves at compile time that key exists on obj , eliminating the entire class of property-access errors. This distinction is critical. Unconstrained generics provide no safety beyond what any offers. Constrained generics encode domain rules directly into the type system, shifting entire categories of bugs left from runtime to compile time. The patterns that follow demonstrate how production codebases use extends and keyof to build type-safe APIs that fail fast during development instead of silently in production. Key Takeaways Generic constraints with extends restrict type parameters to specific shapes, preventing the compiler from accepting types that would cause runtime failures. The keyof operator extracts object keys as a union type, enabling type-safe property access when combined with extends keyof constraints. Combining T extends SomeType with K extends keyof T creates a compile-time proof that a key exists on an object, eliminating property-access errors. Conditi

2026-07-19 原文 →
AI 资讯

Functional programming primitives in Javascript

Category theory often sounds like impenetrable academic jargon, but at its core, it is simply the mathematics of composition. In functional programming, we use its concepts to build modular, predictable, and bug-resistant code. JavaScript isn't a pure functional language like Haskell, but it has first-class functions and treats functions as values. This makes it entirely possible to implement category theory primitives. Here is how the theoretical concepts map to practical JavaScript. The Vocabulary of Category Theory Before jumping into code, let's define the fundamental pieces: Categories: A collection of objects and arrows (morphisms) between them. Objects: In programming, these are our types or data (e.g., String, Number, Boolean, Array). Morphisms: These are our pure functions that transform one type into another (e.g., a function that takes a String and returns a Number). The goal of functional programming primitives is to create safe wrappers (containers) around our data so we can compose these functions predictably, without side effects or unhandled errors. 1. Functors: The Mappables A Functor is any type that implements a map method. It is a container holding a value, and map allows you to apply a function to that value without pulling it out of the container. When you map over a Functor, it returns a new Functor of the same type, preserving the container's structure. The native JS Functor: You already use Functors every day. JavaScript Arrays are Functors. const numbers = [ 1 , 2 , 3 ]; // We apply a function to the values inside, and get a new Array back const doubled = numbers . map ( x => x * 2 ); // [2, 4, 6] Building a custom Functor: Let's build a simple Box container to see how this works for single values. const Box = x => ({ map : f => Box ( f ( x )), fold : f => f ( x ), // An escape hatch to get the value out inspect : () => `Box( ${ x } )` }); // Usage: const result = Box ( ' Functional Programming ' ) . map ( str => str . trim ()) . map ( str

2026-07-19 原文 →
AI 资讯

The Problems with Modern Web Development

Before I critique modern web development, I want to make some points: I'm not discouraging anybody from web development. This is only my opinion and my experience of the story. Everyone has their own story. Part 1. Javascript JavaScript is known for being the web's language. It's used everywhere in the web, and can also be used to make external applications outside of web development. JavaScript has many flaws in its language, such as its comparison logic. JavaScript uses the "strict equality operator" that tries to solve its weird type coercions (e.g [] == ![] being true). Another flaw is that JavaScript has poor maintainability. JavaScript has a poorly managed type system that introduces errors without proper error handling. You cannot explicitly define what error you're trying to catch in the try-catch statement. try { functionThatThrowsError () } catch ( error ) { console . error ( error ); if ( error instanceof MyError ) { doSomething (); } } instead of modern languages: try { functionThatThrowsError () } catch ( e : MyError ) { print ! ( " error: ${e.message} " ) } This adds complexity to try-catch statements and makes it almost impossible to handle errors in a robust manner. Another issue with JavaScript's maintainability is the wording of the language. JavaScript has two keywords called undefined and null . In practice these should mean the same thing but it doesn't. An undefined variable is an uninitialized variable, or a function that doesn't return anything. Undefined: // Returns undefined function getName () {} // syntactically correct in JavaScript // but will cause undefined console . log ( getName ()); const myCoolObject = {}; console . log ( myCoolObject . property ); // still syntactically correct in JavaScript even though the property doesn't exist. Null: // Returns a null name function getName () { return null ; } // output: null console . log ( getName ()); const myCoolObject = { property : null }; console . log ( myCoolObject . property ); //out

2026-07-19 原文 →
AI 资讯

Run a Full JavaScript Website with AxonASP — No Node.js Required

AxonASP is a high-performance Classic ASP engine written in Go — but here's the twist: it runs JavaScript (JScript) natively on the server side. You get a synchronous, predictable execution model, full ECMAScript 5/6+ support, and zero dependency on Node.js or any third-party JavaScript runtime. And yes — you can build an entire production website with it. Why AxonASP Changes the Game for Server-Side JS Most developers associate server-side JavaScript exclusively with Node.js. And Node.js is great — until you're drowning in async/await chains, package.json conflicts, and the 47th minor version bump of a dependency that broke your build. AxonASP takes a fundamentally different approach. Instead of wrapping everything in an event loop and forcing asynchronous patterns everywhere, AxonASP's JavaScript engine executes code synchronously by default . You write your server logic the same way you write your frontend logic — line by line, top to bottom. It compiles through a high-performance AST parser and runs directly on a custom Go-based virtual machine. The result? Cleaner code, simpler debugging, and a massive reduction in cognitive overhead. What You Get Out of the Box Full ES5 + ES6 support (classes, arrow functions, template literals, destructuring, proxies, for...of , Map , Set , Symbol , typed arrays — 37+ modern features documented) Synchronous execution — no callback pyramid, no promise chains for basic I/O ASP intrinsic objects — Request , Response , Session , Application , Server — all accessible directly from your JS code No npm install required — just write .asp or .js files and point the server at them CLI execution — run JavaScript files from the command line for automation, batch processing, or testing The Philosophy: Simplicity Over Complexity Here's a hard truth: most web applications don't need 2,000 npm modules. They need to read a database, render HTML, handle form submissions, and maybe serve a JSON API. That's it. The modern JavaScript ecosystem ha

2026-07-19 原文 →
AI 资讯

Scaling a Single React App to 71+ Browser-Based Tools Without Killing Load Time

The problem with "just add another tool" When you're building one image tool, performance is easy. When you're building 71 of them in the same app — resize, compress, crop, PDF merge, format converters, exam-photo presets, social media templates — the naive approach (import everything, bundle it all together) turns your app into a multi-megabyte JavaScript payload before a user has even picked a tool. This is the actual engineering problem behind ResizeHub , which now has 71+ tools across 11 categories, all running client-side with zero server uploads. Here's how the architecture holds up at that scale. Stack, and why each piece earns its place React + TypeScript — type safety matters more, not less, as tool count grows. A shared ImageProcessor interface that every tool implements catches integration bugs at compile time instead of in production. Vite — its native ES modules dev server and Rollup-based production build made code-splitting dramatically easier to reason about than older bundlers, which matters a lot once you have dozens of independent tool routes. HTML5 Canvas API — the actual compression/resize/crop engine, shared across tools rather than reimplemented per-tool. Cropper.js — for interactive cropping UI specifically (aspect-ratio locking, circular crop for signatures) rather than rebuilding drag-handle math from scratch. Pica — for high-quality image downscaling; the browser's native canvas scaling can introduce visible aliasing on large downscales, and Pica's algorithm handles this noticeably better. Cloudflare Pages — static hosting with edge caching, which matters since 100% of the actual processing work happens in the user's browser, not on any server at all. Lesson 1: Route-level code splitting isn't optional past a handful of tools With React Router and dynamic import() , each tool becomes its own chunk: const PhotoResizer = lazy (() => import ( ' ./tools/PhotoResizer ' )); const PdfCompressor = lazy (() => import ( ' ./tools/PdfCompressor ' ));

2026-07-18 原文 →
AI 资讯

Modern Frontend Testing Is Mostly About State, Timing, and Geometry

Frontend testing used to sound simple: open a page, find an element, click it, and verify the result. That description still works for basic workflows, but modern interfaces are no longer a single static DOM that changes in obvious ways. Components can render inside Shadow DOM. Modals can be portaled to a different part of the document. Server-rendered HTML can be replaced during hydration. Content can move because of CSS container queries. A page can look finished while several progressive-loading states are still changing underneath it. The hardest frontend bugs now tend to sit at the intersection of three things: State: what the application believes is happening. Timing: when the browser and framework apply changes. Geometry: where elements appear and whether users can actually interact with them. A stable test strategy has to observe all three. Shadow DOM and portals break naive assumptions about element location Component encapsulation is useful, but it changes how automation finds and interacts with elements. A control inside an open shadow root is not always reachable through the same selector strategy used for the main document. A portaled modal may appear visually next to a component while being rendered near the end of document.body . Focus can move into the modal even though the DOM hierarchy suggests that it belongs elsewhere. This guide to testing Shadow DOM and portaled modals without breaking browser automation suites covers the key challenges. The test should verify behavior, not merely the presence of a node: Can the user reach the control? Is the expected element visible above overlays? Does keyboard focus enter the modal? Is focus trapped correctly? Does Escape close it? Does focus return to the triggering element? Can a screen reader identify its label and role? Selectors still matter, but interaction boundaries matter more. A test that locates a button hidden behind another layer is not testing what the user experiences. Hydration creates a peri

2026-07-18 原文 →
AI 资讯

Polling, SSE, or WebSockets for Mobile Upload Status?

After the browser transfers a file, the server may still scan, transcode, extract metadata, or generate previews. The interface needs status updates, but the most fashionable real-time transport is not automatically the most reliable choice for an event guest on a mobile browser. Start with the update contract Define states and transitions before choosing transport: accepted -> queued -> processing -> ready accepted -> rejected processing -> processing_error Every status response should include a monotonically increasing version or timestamp. The client can ignore events older than the state it already knows. Polling is a strong baseline HTTP polling works through proxies, resumes naturally after a page wake, and is easy to cache and rate-limit. Use adaptive intervals: one second just after acceptance, then back off to several seconds when processing takes longer. const delay = Math . min ( 8000 , 1000 * 2 ** slowChecks ); Add jitter when many guests finish at the same time. Stop when the state is terminal, the page is gone, or a server-provided retry time says to wait longer. SSE fits one-way progress Server-Sent Events are attractive when the server only pushes status. The browser reconnects with a last-event ID, and the wire format is simple. But mobile networks and some intermediaries silently kill idle connections. Send occasional heartbeats and treat reconnection as normal. The reconnect handler must fetch current state because events may have been missed beyond the server replay window. Do not keep one SSE stream per file. Subscribe by guest session or album and filter authorized upload IDs on the server. WebSockets add more responsibility WebSockets make sense when the client also sends frequent commands over the same channel or when a host moderation console needs many rapid updates. For a guest waiting on two files, they add connection authentication, heartbeat, reconnect, replay, and load-balancer complexity without much user benefit. Never rely on the so

2026-07-18 原文 →