1

I just started progamming with VueJS, and I can not understand the reason why I cannot put my "new Vue ()" function in a .js file. I make an example with the simplest application I can think about. If my HTML goes like this

<html>
<head>
<meta charset="utf-8" />
<title>HBL</title>
<script src="https://unpkg.com/vue"></script>
<script src="esterno.js"></script>
</head>
<body>
  <div id="application">
     <greeting></greeting>
  </div>
</body>

And my .js like this

Vue.component('greeting', {
template: '<h1>Basic Component</h1>'
});

var vm = new Vue({
 el: '#application'
 });

It does not show anything, the console displays this error :"[Vue warn]: Cannot find element: #application", but if I open JSFiddle and just paste the code it works.

If I take the last three lines of the .js file and put them in a < script > tag in the html body, I have no error and everything works well.

Why does this happen? Thank you for your attention.

2 Answers2

2

If your esterno.js is the js code that you show, this is because

the javascript code is executed before the DOM is loaded . You're right that putting the code below in the <body> tag will make sure that the code is only executed once the DOM, and therefore the element with id application, is loaded.

Community
  • 1
  • 1
Sventies
  • 2,314
  • 1
  • 28
  • 44
2

Scripts should be at the end of body. And I recommend you to load scripts when DOM is loaded.

<html>
<head>
<meta charset="utf-8" />
<title>HBL</title>
</head>
<body>
  <div id="application">
     <greeting></greeting>
  </div>
<script src="https://unpkg.com/vue"></script>
<script src="esterno.js"></script>
</body>
Oen44
  • 3,156
  • 1
  • 22
  • 31