Skip to main content
The loadModel() function initializes the TensorFlow.js model by loading it from the model.json file. This function must be called before performing any predictions.

Function signature

async function loadModel()
This is an asynchronous function that returns a Promise. The model is loaded from cnn_model/model.json and stored in the global model variable.

Parameters

This function takes no parameters.

Return value

model
tf.LayersModel
Returns a Promise that resolves when the model is successfully loaded. The loaded model is stored in the global model variable.

How it works

The function performs the following steps:
  1. Logs “Loading Model” to the console
  2. Loads the TensorFlow.js model from cnn_model/model.json using tf.loadLayersModel()
  3. Logs “Loaded Model” to the console
  4. Updates the UI to indicate the model has loaded
  5. Hides the loading progress bar

Code example

// Load the model when the page initializes
loadModel();

Implementation

Here’s the complete implementation from the source code:
async function loadModel(){
    console.log("Loading Model")
    model = await tf.loadLayersModel('cnn_model/model.json')
    console.log("Loaded Model")

    loadingmodel.innerHTML = "Loaded ML Model"
    progressbar.style.display = "none"
}

Usage in HTML

The function is automatically called when the page loads:
<script>
    loadModel()
</script>

UI integration

The function updates two HTML elements:
  • loadingmodel - Text element that displays “Loaded ML Model” when complete
  • progressbar - Progress indicator that is hidden after loading
Ensure the model file exists at cnn_model/model.json before calling this function. The model file should be in the same directory structure as your HTML file.

Best practices

  • Call this function once when your application initializes
  • Wait for the model to load before enabling prediction functionality
  • The global model variable must be initialized before calling loadModel()
var model = null

// Then call loadModel()
loadModel()

Build docs developers (and LLMs) love