[How to] Multi page website using single HTML page

Here's a neat little single page HTML / JS site that allows for multiple pages using a JS router and AJAX to pull the pages in.

It is meant for people who are given a free single page website with a domain but want multiple static pages (eg. about, contact)

I really just made this as a proof of concept but hopefully it will come in handy for someone.

You can see it in action HERE

Features

  • Uses a JS Router - Allows users to bookmark / link to certain pages
  • Uses cors-anywhere to allow fetching of page data from different domains
  • Prefetches other pages once initial page is loaded
  • Unlimited pages possible


How to

  1. Download the onepage.html file (Right Click -> Save link as...)
  2. Open the onepage.html file in your favourite text editor
  3. Add in the pages you want & location of the data in the JS pages dictionary (see below)
  4. Upload the file to your website
var pages = {
    'home' : 'http://pastebin.com/raw/CgtAJX42',
    'about' : 'http://pastebin.com/raw/WiSXnLG0',
    'contact' : 'http://pastebin.com/raw/ZW9VR9UH',
    '404' : 'http://pastebin.com/raw/qMs4PPfH',
}
The keys ( 'about', 'contact') are the URL that is matched example.com/#/about, example.com/#/contact
The value is the URL to the data for that page that will be fetched.

The data from the URL will be pulled in to a <div id="content-{page}"> element which is added into the <content> container. It is only fetched once and the div is just shown / hidden when selected.

'home' and '404' are special keys that are used for the first index page and 404 is used when a page can't be found.

You can add common HTML data to the index.html page.
It is best not to add HTML into the "content" container, but try to use the "header" or "footer" containers.

Style it by adding styles to header area or inline or an external CSS file hosted somewhere.

Comments

  1. Sounds like a very nice technique to show different html-pages as a onepage. However, in Chrome 56 the demo page does not work. For each page the console says:
    Refused to execute script from 'https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdpr…nwc6iw&callback=jQuery1111012204842732570764_1487599016830&_=1487599016831' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

    Could this be fixed?

    ReplyDelete
    Replies
    1. Thanks for letting me know.

      I have now updated the code to use a CORS proxy :)
      Should be more reliable now as long as http://cors-anywhere.herokuapp.com/ stays up.

      Note: For small sites, I would just have all the HTML code for each page embedded in the single html page and use the JS to switch it out.

      You wouldn't want this for large sites due to load times (the html would be pretty large)

      Delete

Post a Comment