# How the startOnLoad Initialization Option Controls Automatic Diagram Rendering in Mermaid

> Discover how the Mermaid startOnLoad option controls automatic diagram rendering on page load. Learn to manage rendering with this essential JavaScript configuration.

- Repository: [mermaid-js/mermaid](https://github.com/mermaid-js/mermaid)
- Tags: deep-dive
- Published: 2026-02-23

---

**The `startOnLoad` initialization option is a boolean configuration flag that determines whether Mermaid automatically scans the DOM and renders diagrams when the page loads or defers rendering until manually triggered via JavaScript.**

The `startOnLoad` initialization option provides essential control over diagram rendering timing in the `mermaid-js/mermaid` library. Located within the core configuration system defined in [`src/mermaidAPI.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/mermaidAPI.ts), this setting manages the automatic execution of Mermaid's rendering pipeline upon the browser's `DOMContentLoaded` event. Understanding how to configure this option ensures optimal integration across static websites, single-page applications, and dynamic content environments.

## What Is the startOnLoad Initialization Option?

The `startOnLoad` initialization option is a boolean parameter passed to `mermaid.initialize()` that defaults to `true`. Defined in [`src/mermaidAPI.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/mermaidAPI.ts), this flag controls whether the library registers an automatic rendering trigger when the HTML document finishes loading. When enabled, Mermaid executes its initialization sequence in [`src/init.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/init.ts), which attaches a `DOMContentLoaded` event listener to scan for diagram definitions and convert them into SVG graphics without requiring additional JavaScript calls.

## How startOnLoad Controls Automatic Rendering

### When startOnLoad Is true (Default Behavior)

When `startOnLoad` is set to `true`, Mermaid immediately registers a `DOMContentLoaded` listener after `mermaid.initialize()` executes. Upon page load completion, the library queries the DOM for elements containing diagram definitions—typically `<div class="mermaid">` containers or code blocks with the `mermaid` language identifier. Each discovered definition undergoes parsing and SVG transformation, with the resulting graphics injected directly into the DOM to replace the original text markup. This configuration provides a zero-code rendering experience where diagram markup alone triggers automatic visualization.

### When startOnLoad Is false (Manual Control)

Setting `startOnLoad` to `false` prevents Mermaid from attaching the automatic `DOMContentLoaded` listener. In this mode, diagram definitions remain as unrendered text until explicitly processed via JavaScript. Developers must invoke `mermaid.run()` to render all diagrams or `mermaid.render(id, graphDefinition, container)` for specific elements. This manual approach is essential for single-page applications using React or Vue, where DOM elements may not exist at initial load, or when diagram content depends on asynchronous data fetching that completes after the page renders.

## Source Code Implementation

The `startOnLoad` logic spans two critical files in the Mermaid codebase. In [`src/mermaidAPI.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/mermaidAPI.ts), the `initialize()` function accepts the configuration object and persists the `startOnLoad` value in the global configuration state. The actual event handling occurs in [`src/init.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/init.ts), where the initialization logic checks this flag before registering the `DOMContentLoaded` listener. When the flag is enabled, the `init` function proceeds to execute `run()` automatically; when disabled, the function exits without attaching listeners, leaving rendering control entirely to the developer.

## Practical Code Examples

### Example 1: Default Automatic Rendering

The following HTML demonstrates standard usage with `startOnLoad: true`, causing automatic diagram rendering upon page load:

```html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
  <script>
    // Explicitly enabling automatic rendering (default behavior)
    mermaid.initialize({ startOnLoad: true });
  </script>
</head>
<body>
  <div class="mermaid">
    graph TD
      A[Start] --> B{Is it working?}
      B -->|Yes| C[Great!]
      B -->|No| D[Check config]
  </div>
</body>
</html>

```

When the browser completes loading, the `<div class="mermaid">` automatically transforms into an SVG graphic.

### Example 2: Deferred Rendering with startOnLoad: false

This example disables automatic rendering and triggers diagram generation only after asynchronous data retrieval:

```html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
  <script>
    // Disable automatic rendering
    mermaid.initialize({ startOnLoad: false });

    document.addEventListener('DOMContentLoaded', () => {
      // Fetch diagram definition from API
      fetch('/api/diagram-data')
        .then(response => response.text())
        .then(definition => {
          const container = document.getElementById('dynamicDiagram');
          mermaid.render('generatedDiagram', definition, container);
        });
    });
  </script>
</head>
<body>
  <div id="dynamicDiagram"></div>
</body>
</html>

```

The diagram renders only after the fetch operation completes, preventing errors from attempting to render non-existent or incomplete data.

### Example 3: Selective Rendering with mermaid.run()

When `startOnLoad` is disabled, you can render specific diagram elements using `mermaid.run()` with a query selector:

```javascript
// Initialize with automatic rendering disabled
mermaid.initialize({ startOnLoad: false });

// Dynamically insert new diagram markup
document.getElementById('newSection').innerHTML = `
  <div class="mermaid">
    flowchart LR
      X --> Y
      Y --> Z
  </div>
`;

// Render only the newly added diagram
mermaid.run({ querySelector: '#newSection .mermaid' });

```

This approach optimizes performance by avoiding unnecessary DOM scans and rendering only the specific content that requires visualization.

## Summary

The `startOnLoad` initialization option provides flexible control over diagram rendering timing in Mermaid applications:

- **Default behavior (`true`)**: Automatically renders all diagrams when `DOMContentLoaded` fires, requiring no manual JavaScript intervention for static content.
- **Manual mode (`false`)**: Prevents automatic rendering, enabling explicit control via `mermaid.run()` or `mermaid.render()` for dynamic or asynchronous content scenarios.
- **Implementation files**: Configuration handling occurs in [`src/mermaidAPI.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/mermaidAPI.ts) while event listener registration resides in [`src/init.ts`](https://github.com/mermaid-js/mermaid/blob/main/src/init.ts).
- **Framework compatibility**: Setting `startOnLoad` to `false` is recommended for React, Vue, and Angular applications to prevent premature rendering attempts before components mount.

## Frequently Asked Questions

### What happens if I don't specify startOnLoad in Mermaid?

If you omit the `startOnLoad` option when calling `mermaid.initialize()`, the library defaults to `true`. This means Mermaid will automatically attach the `DOMContentLoaded` listener and attempt to render all diagram definitions immediately upon page load, which works seamlessly for static HTML but may cause issues in dynamic environments.

### Can I use startOnLoad: false in a React or Vue application?

Yes, setting `startOnLoad: false` is actually the recommended approach for React, Vue, and other single-page application frameworks. Because these frameworks dynamically inject content into the DOM after the initial `DOMContentLoaded` event fires, automatic rendering would attempt to process non-existent elements. Disabling the option allows you to call `mermaid.run()` within component lifecycle hooks or effect handlers once the diagram markup is actually present.

### How do I render diagrams after the page has loaded if startOnLoad is false?

When `startOnLoad` is set to `false`, you have two primary methods for manual rendering. Use `mermaid.run()` without arguments to process all elements with the `mermaid` class, or pass a `querySelector` option to target specific elements. For complete control over individual diagrams, use `mermaid.render(id, graphDefinition, container)`, which accepts a unique ID, the diagram definition string, and a target DOM element.

### Does startOnLoad affect performance in single-page applications?

Yes, the `startOnLoad` setting can significantly impact performance in single-page applications. When enabled, Mermaid executes a full DOM scan and attempts parsing immediately upon page load, which wastes CPU cycles if diagram elements haven't been created yet, and may throw errors if selectors return null. Disabling the option prevents this premature execution, allowing you to defer rendering until components mount and data loads, resulting in more efficient resource utilization and fewer runtime errors.