简体   繁体   中英

Express.js Avoid reload the whole page

currently I have no solution for a site which I am trying to build. The page is not that big but I want to achieve that the complete site does not reload when I am opening a new tab in the navbar. I am using express.js and mustache as the template engine. My goal is, that only the content reloads and not the whole site including the Navbar.

Do I have to use Ajax here? and

Is my structure correct to do this?

On the Server.js file I have this general structure I am not sure if there is a trick with views to only reload the content part of a page:

app.get('/home', function(req, res) {
    res.render('index.html')
});

app.get('/navitem1', function(req, res) {
    res.render('navitem1.html')
});

app.get('/navitem2', function(req, res) {
    res.render('navitem2.html')
});

If you are trying to make sure your webpage doesn't reload while switch tabs and you're webpage isn't that big. I would recommend containing all your information within one .html file, have each "page" contained by a div with a targetable id, then simply hide/show the content that is selected. You might want to check out page.js and jquery they make this process much easier.

This is a quick demo of how to implement this:

note: you will need to npm init and npm i page

index.html:

<html>
 <head>
  <title></title>
 </head>
 <body>
  <div id="title-area">
   <h1>--your title--</h1>
   <nav>
    <ul>
     <li><a href="/">Home</a></li>
     <li><a href="/anotherpage">Another Page</a></li>
    </ul>
   </nav>
  </div>
  <div id="home">
   --home content--
  </div>
  <div id="another-page">
   --other page content--
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="vendors/scripts/page.js"></script>
  <script src="scripts/controllers/routes.js"></script>
 </body>
</html>

scripts/controllers/routes.js:

sorry about globally scoped the IFFE functions, this is copy pasted.

'use strict';
(function(module){
const homeController = {};
homeController.init = function(){
  $('#another-page').hide();
  $('title').html('Home');
  $('#home').fadeIn('slow');
}
module.homeController = homeController;
})(window);

(function(module){
const anotherpageController = {};
anotherpageController.init = function(){
  $('#home').hide();
  $('title').html('anotherpage');
  $('#another-page').fadeIn('slow');
}
module.anotherpageController = anotherpageController;
})(window);

page('/', homeController.init);
page('/anotherpage', anotherpageController.init);

page();

if you'd like a better demo you can check out the app I built (where most of this content was ripped) https://github.com/loganabsher/portfolio-2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM