Skip to content

Instantly share code, notes, and snippets.

@afcapel
Last active February 8, 2023 10:15
Show Gist options
  • Save afcapel/3b46c9dd5bf91102250b08cea3c50116 to your computer and use it in GitHub Desktop.
Save afcapel/3b46c9dd5bf91102250b08cea3c50116 to your computer and use it in GitHub Desktop.
Stimulus targets making document clone slow
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Stimulus Test</title>
</head>
<body>
<div id="container">
<button id="cloneBodyBtn">Clone body</button>
</div>
<script type="module">
import { Application, Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
window.Stimulus = Application.start()
window.Stimulus.register("test", class TestController extends Controller {
connect() { console.log("Connected") }
})
let container = document.getElementById("container")
// data-test-target="form" is what makes the body cloning slow. Removing the attribute
// makes the cloning fast again. Interestingly, data-test-target="button" doesn't have
// any effect whatsoever
for (let i=0; i<10000; i++) {
container.insertAdjacentHTML("beforeend", `
<div id="wrapper-${i}" data-controller="test">
<form id="frame-${i}" data-test-target="form">
<button data-test-target="button">Button ${i}</button>
</form>
</div>`)
}
document.getElementById("cloneBodyBtn").addEventListener("click", () => {
console.profile("Cloning body...")
const cloned = document.body.cloneNode(true)
console.profileEnd("Cloning body...")
console.log({ owner: cloned.ownerDocument, isConnected: cloned.isConnected })
})
const nControllers = document.querySelectorAll("[data-controller]").length
container.insertAdjacentHTML("afterbegin", `<h1>Page with ${nControllers} stimulus controllers</h1`)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment