A basic 5 minute example of a vanilla JavaScript SPA
Below is the code for an example where we load a login page, dummy handle the response and go to a home page where we show fetched data.
Example HTML that loads the main.js file which includes our app view handler, as well as two template files, login.js and and home.js
Title
Our view handler. I always default to app for new projects and package or attach all main methods to it.
Here we are defining an output method which will attempt to set default values if not passed, render the view to our defined content element and call a related script, all by calling app.output()
const app = {
template: [],
content: false,
output: (name, values = {}) => {
if (typeof app.template[name].values === "function") {
values = app.template[name].values(values)
}
if (typeof app.template[name].view === "function") {
app.content.innerHTML = app.template[name].view(values)
}
if (typeof app.template[name].script === "function") {
app.template[name].script(values)
}
},
}
window.addEventListener("load", () => {
app.content = document.querySelector('#content')
app.output('login')
})
Below are the login.js and home.js files to import.
The can optionally include the values method for handling default variables (see home.js), the view method which will return the html output to be rendered and the script method which is automatically called by output to run any related scripts.
Scripts can include initial functions to run and event handlers for things like login buttons.
app.template.login = {
view: (op = {}) => {
return `
Login Here
`
},
script: (op = {}) => {
document.querySelector('#login').addEventListener('click', () => {
//login check - assume passed for demo
app.output('home', {name: 'Luke'})
})
}
}
app.template.home = {
values: (op = {}) => {
return {
name: 'User',
...op,
}
},
view: (op = {}) => {
return `Hello, ${op.name}!
`
},
script: (op = {}) => {
let feed = document.querySelector('#home')
feed.innerHTML = `Hi Loading...`
//fetch home feed content
setTimeout(() => {
let output = ``
output += ` `
for (let i = 0; i < 20; i++) {
output += `- I am an item
`
}
output += `
`
//show home feed content
feed.innerHTML = output
}, 1000)
}
}