Skip to content

Instantly share code, notes, and snippets.

@itsjohncs
Created September 17, 2021 01:21
Show Gist options
  • Save itsjohncs/f95df23cc40adf1c2a3fe761e52733c9 to your computer and use it in GitHub Desktop.
Save itsjohncs/f95df23cc40adf1c2a3fe761e52733c9 to your computer and use it in GitHub Desktop.
One works and the other freezes the browser... Why?
<!DOCTYPE html>
<html>
<head>
<script>
let _openCVPromise = null;
function getOpenCV() {
if (_openCVPromise === null) {
_openCVPromise = new Promise(function(resolve, reject) {
const script = document.createElement("script");
script.setAttribute("src", "https://shmeppy-external-js.sfo3.cdn.digitaloceanspaces.com/opencv-4.5.3.js");
script.addEventListener("load", function() {
resolve(window.cv); // !! Only difference
});
document.head.appendChild(script);
});
}
return _openCVPromise;
}
</script>
</head>
<body>
<button onClick="console.log(getOpenCV())">load</button>
<button onClick="console.log('OpenCV loaded', !!window.cv)">Beep</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
let _openCVPromise = null;
function getOpenCV() {
if (_openCVPromise === null) {
_openCVPromise = new Promise(function(resolve, reject) {
const script = document.createElement("script");
script.setAttribute("src", "https://shmeppy-external-js.sfo3.cdn.digitaloceanspaces.com/opencv-4.5.3.js");
script.addEventListener("load", function() {
resolve(); // !! Only difference
});
document.head.appendChild(script);
});
}
return _openCVPromise;
}
</script>
</head>
<body>
<button onClick="console.log(getOpenCV())">load</button>
<button onClick="console.log('OpenCV loaded', !!window.cv)">Beep</button>
</body>
</html>
@mast4461
Copy link

mast4461 commented Feb 29, 2024

After many hours of bug hunting I found this out for my own sake, feeling quite triumphant!
The reason that resolve(window.cv); freezes the browser is that cv is infinitely thenable, so an infinite recursion is started. resolve checks if the provided argument is thenable, and if so hooks up to it via its then method, passing resolve as argument I suppose. And if OpenCV has been initialized, then its then method calls the provided function with OpenCV itself as a argument, which has a then method, which is called and calls back with itself, which has a then method, which is called and calls back with itself, and so on...
My solution was to wrap it: resolve({cv: window.cv}).

@itsjohncs
Copy link
Author

Ahhhh that makes sense. Thank you for solving this mystery.

Though I have a new mystery. I forget why I made this gist. Where did you find a link to this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment