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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I knew I was doing something wrong but I couldn't figure it out, now everything looks so obvious
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.