I'm trying to play with TensorFlow.js's tf.browser.fromPixels()
function. Unfortunately, I get the following error:
backend_webgl.ts:309 Uncaught Error: The DOM is not ready yet. Please call tf.browser.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object
at e.fromPixels (backend_webgl.ts:309)
at t.fromPixels (engine.ts:870)
at fromPixels_ (browser.ts:55)
at Object.fromPixels (operation.ts:45)
at ex4.html:10
But I'm calling tf.browser.fromPixels()
from inside a function passed to window.addEventListener('DOMContentLoaded', ...)
. Any idea why I'm getting this error and how to get the fromPixels
function to work?
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2.7/dist/tf.min.js"></script>
</head>
<body>
<img id="test" src="https://jpeg.org/images/jpeg-home.jpg">
<script>
window.addEventListener('DOMContentLoaded', ev => {
const img = document.getElementById('test')
tf.browser.fromPixels(img).print()
})
</script>
</body>
</html>
if (document.readyState !== 'complete') {
throw new Error(
'The DOM is not ready yet. Please call ' +
'tf.browser.fromPixels() once the DOM is ready. One way to ' +
'do that is to add an event listener for `DOMContentLoaded` ' +
'on the document object');
}
According to the code above, the error is thrown because document.readyState
isn't complete
.
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
The readyState of a document can be one of following:
loading
The document is still loading.interactive
The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.complete
The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.
https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
DOMContentLoaded
is called before any sub-resources aren't loaded yet.So At the time of your code is executed, document.readyState
is still interactive
.
Just ignore what the error says and try load
event listener instead.