I use vibed server. It use Pug preprocessor (before known as Jade). Here is my page code:
doctype html
html
head
script(src="https://unpkg.com/vue")
script(src="app.js")
title Hello, World
body
h1 Hello World
#app
|{{message}}
It generate next HTML output:
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue"></script><script src="app.js"></script><title>Hello, World</title>
</head>
<body>
<h1>Hello World</h1>
<div id="app">
{{message}}
</div>
</body>
</html>
My app.js code:
window.onload = function() {
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
});
app.$mount('#app');
}
But it's do not work. In browser console I am getting next error:
Cannot find element: #app
upd: moving script(src="app.js")
to down helped. But is there any better variant? Or it's ok?
There are really two ways to handle it. One is to move the script to the bottom of the page, and the second is to use an event to trigger your code when the page is loaded.
The way you typically listen for the page to be loaded these days (without jQuery) is to listen for the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function() {
var app = new Vue(...)
});
The primary difference between the DOMContentLoaded
and the load
event being that DOMContentLoaded
fires when all the DOM content has been parsed, and the load
event waits for everything to be loaded including images, and stylesheets, and other things.