[Vuejs]-Vue project – Uncaught TypeError: Cannot read properties of null (reading 'offsetWidth') error for a custom js script

3πŸ‘

βœ…

You are importing your demo3.js file (and thus executing it) before the app rendered the DOM. So the element #scene doesn’t exist yet, resulting in being null.

Several solutions for this:

  1. You import dynamically your demo3.js file after mounted hook:
mounted() {
  import('../assets/assets/js/demo3.js') // dynamic import
}
  1. You wrap your demo3.js code inside a function and export it.
// demo3.js

export function renderScene() {
  var canvas = document.querySelector("#scene");
  var width = canvas.offsetWidth,
    height = canvas.offsetHeight;
  // [...]
}
import { renderScene } from '../assets/assets/js/demo3.js'

export default {
  mounted() {
    renderScene()
  }
}
  1. You move your demo3.js code to a vue component, and use template refs.
mounted() {
  const scene = this.$refs.scene
  if (scene) {
    const width = canvas.offsetWidth,
      height = canvas.offsetHeight;

    const renderer = new THREE.WebGLRenderer({
      canvas: canvas,
      antialias: true,
    });
    // [...]
  }
}
πŸ‘€Kapcash

Leave a comment