<head>
...
<script src="main.js"></script>
...
</head>JavaScript performance optimization / notebook
JavaScript performance optimization
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
<head>
...
<!-- Preload a JavaScript file -->
<link rel="preload" href="important-js.js" as="script" />
<!-- Preload a JavaScript module -->
<link rel="modulepreload" href="important-module.js" />
...
</head><!-- Include this wherever makes sense -->
<script src="important-js.js"></script>import { someFunction } from "important-module.js";<head>
...
<script async src="main.js"></script>
...
</head>const scriptElem = document.createElement("script");
scriptElem.src = "index.js";
scriptElem.addEventListener("load", () => {
// Run a function contained within index.js once it has definitely loaded
init();
});
document.head.append(scriptElem);import("./modules/myModule.js").then((module) => {
// Do something with the module
});function main() {
a();
b();
c();
d();
e();
}function yieldFunc() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}async function main() {
// Create an array of functions to run
const tasks = [a, b, c, d, e];
// Loop over the tasks
while (tasks.length > 0) {
// Shift the first task off the tasks array
const task = tasks.shift();
// Run the task
task();
// Yield to the main thread
await yieldFunc();
}
}function yieldFunc() {
// Use scheduler.yield() if available
if ("scheduler" in window && "yield" in scheduler) {
return scheduler.yield();
}
// Fall back to setTimeout:
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}function loop() {
// Clear the canvas before drawing the next frame of the animation
ctx.fillStyle = "rgb(0 0 0 / 25%)";
ctx.fillRect(0, 0, width, height);
// Draw objects on the canvas and update their positioning data
// ready for the next frame
for (const ball of balls) {
ball.draw();
ball.update();
}
// Call requestAnimationFrame to run the loop() function again
// at the right time to keep the animation smooth
requestAnimationFrame(loop);
}
// Call the loop() function once to set the animation running
loop();function handleMouseMove() {
// Do stuff while mouse pointer is inside elem
}
elem.addEventListener("mousemove", handleMouseMove);elem.removeEventListener("mousemove", handleMouseMove); function processGroup(array) {
const toFind = "Bob";
for (let i = 0; i < array.length - 1; i++) {
if (array[i] === toFind) {
processMatchingArray(array);
break;
}
}
} async function returnResults(number) {
for (let i = 0; i < number; i++) {
const response = await fetch(`/results?number=${number}`);
const results = await response.json();
processResult(results[i]);
}
}