请提供需要翻译的内容。

```

```html Translation

请提供需要翻译的内容。

```
Just Use HTML

原始链接: https://gomakethings.com/just-use-html/

## 重新思考 JavaScript 与 HTML – 性能提升 作者认为不应过度依赖 JavaScript 来处理更适合 HTML 的任务,理由是性能、可读性和可维护性问题。他们认为,JavaScript 速度较慢、更容易出错,并且会模糊最终输出结果,而原生 HTML 则不然。然而,他们并非提倡完全放弃 JavaScript——它的优势在于*增强*现有功能,特别是添加交互性。 文章重点介绍了两种常见场景:表单提交和 API 数据显示。传统上,React(以及类似框架)通常使用带有大量 JavaScript 状态管理的“受控输入”来处理表单,甚至牺牲了 Enter 键提交等原生可访问性功能。一种更简单、更易于访问的方法是使用标准的 HTML 表单元素,并仅使用最少的 JavaScript 来处理提交。 同样,从 API 响应生成表格通常是在客户端使用 JavaScript 完成的。作者建议将这项工作转移到后端,让服务器直接返回 HTML 表格,从而实现更快的渲染和更简单的客户端实现。 最终,这种方法提倡工作流程的转变——更多后端工作,但能带来更快速、更可靠、更易于理解的应用程序。

一篇 Hacker News 的讨论围绕着文章“Just Use HTML”(gomakethings.com),该文章提倡利用 HTML 的能力来减少对 JavaScript 在 Web 开发中的依赖。 一些人认为这是一个令人耳目一新的观点,但许多评论者指出其局限性。纯 HTML 在复杂的验证方面表现不佳,并且很快就会变得难以管理。 几位用户强调了直接在服务器端渲染 HTML 的好处,而不是将 JSON 发送到客户端由 JavaScript 处理——尤其是在资源受限的服务器上,例如 Raspberry Pi。 另一些人认为 JSON API 提供了灵活性,允许用户在本地操作数据,并且对非 HTML 客户端很有用。一个关键点是 JSON 和 HTML 之间转换的效率低下,表明服务器渲染的 HTML 通常更有效。 最终,这场对话强调了现代 Web 开发中简单性、性能和灵活性之间的权衡。
相关文章

原文

I’ve worked on so many projects recently that were more complicated than they needed to be because they used JavaScript to generate HTML.

JavaScript is…

  • Slower to load
  • Slower to run
  • More prone to breaking
  • Harder to read and reason about
  • Doesn’t actually look like the final output

It’s inferior to just using HTML in nearly every way.

I’m not saying never use JavaScript, though. I think JS is great at augmenting and enhancing what’s already there, and adding interactivity that cannot (yet) but handled with HTML.

Let’s look at two examples…

Submitting a form

I see this a lot in React and JSX.

Every input in a form has an input listener on it. Any changes to that input update a state property. That property is used to set the value of the input, creating this weird circular logic.

(This approach is called “controlled inputs” in React-land, and some devs are slowly moving away from it, finally.)

The form submit is often also tied to clicking a <button> rather than submitting a form, meaning that hitting enter on an input won’t submit the form. This removes a native accessibility feature.

function Login () {
	const [username, setUsername] = useState('');
	const [password, setPassword] = useState('');

	function handleSubmit () {
		if (!username || !password) {
			// Show error message
			return;
		}

		fetch('/login', {
			method: 'POST',
			body: JSON.stringify({
				username,
				password
			}),
		});
	}

	return (
		<form onSubmit={event => event.preventDefault()}>
			<label for="username">Username</label>
			<input 
				id="username"
				type="text" 
				onInput={event => setUsername(event.value)} 
				value={username}
			/>

			<label for="password">Password</label>
			<input 
				id="password"
				type="password" 
				onInput={event => setPassword(event.value)} 
				value={password}
			/>

			<button onClick={handleSubmit}>Submit</button>
		</form>
	);
}

Here’s that same setup with HTML…

<form action="/login" method="POST">
	<label for="username">Username</label>
	<input 
		id="username"
		type="text"
		required
	/>

	<label for="password">Password</label>
	<input 
		id="password"
		type="password" 
		required
	/>

	<button>Submit</button>
</form>

And then you can enhance it with just a touch of JavaScript…

const form = document.querySelector('[action*="/login"]');
form.addEventListener('submit', event => {
	event.preventDefault();
	const data = new FormData(form);
	const body = JSON.stringify(Object.fromEntries(data));
	fetch('/login', {
		method: 'POST',
		body
	});
});

Hell, you can even do this in React if you want!

function Login () {

	function handleSubmit (event) {
		event.preventDefault();
		const data = new FormData(event.target);
		const body = JSON.stringify(Object.fromEntries(data));
		fetch('/login', {
			method: 'POST',
			body
		});
	}

	return (
		<form onSubmit={handleSubmit}>
			<label for="username">Username</label>
			<input 
				id="username"
				type="text"
				required
			/>

			<label for="password">Password</label>
			<input 
				id="password"
				type="password" 
				required
			/>

			<button>Submit</button>
		</form>
	);
}

API responses

Another area where you can lean a lot more heavily on HTML is API responses.

Let’s say you have a <table> that gets generated based on some data that’s specific to the user or some selections that have been made in a <form>.

In most modern apps, that means getting back some JSON, and generating a <table> from it.

const app = document.querySelector('#app');

const request = await fetch('/my-wizards');
const response = await request.json();

app.innerHTML =
	`<table>
		<thead>
			<tr>
				<th>Name</th>
				<th>Location</th>
				<th>Powers</th>
			</tr>
		</thead>
		<tbody>
		${response.wizards.map(wizard => {
			const {name, location, powers} = wizard;
			const row = 
				`<tr>
					<td>${name}</td>
					<td>${location}</td>
					<td>${powers}</td>
				</tr>`;
			return row;
		}).join('')}
		</tbody>
	</table>`;

But if a server has to do the work of getting that information and sending it back to you anyways, it could also just send the <table> HTML, which you could then render into the UI.

const app = document.querySelector('#app');

const request = await fetch('/my-wizards');
const response = await request.text();

app.innerHTML = response;

There are workflow changes

This, of course, changes the workflow of building apps quite a bit.

A lot of work shifts to the backend that in today’s apps is handled with client-side code. But… that’s a good thing?

It means faster, simpler apps that behave more predictably and reliably.

联系我们 contact @ memedata.com