简体   繁体   中英

Polymer app routing partials with Page.js

I'm using the Polymer Starter Kit and would like have each route's content in a separate file (/pages/games.html, /pages/movies.html, etc) but I can't find any examples of this.

Could someone point me in the right direction? Or is it not possible or recommended to implement routing like this?

You could approach this a lot of different ways (replacement of a holder in index.html at build time, swapping for a different router). One such approach would be to implement your files and then fetch() them into the DOM. This is sort of the approach that is used in the partials example that is outlined in page.js repo.

So, let's modify iron-pages in index.html in the starter kit to have a loading section:

<iron-pages attr-for-selected="data-route" selected="{{route}}">

  <!-- Block we'll load our partials into -->
  <section id="load" data-route="load"></section>

...

Then let's modify elements/routing.html to change our page.js. Let's route /test to our target load section:

window.addEventListener('WebComponentsReady', function() {

  page('/test', function () {

    // iron-pages needs to show the proper section
    // in this case, our designated loading target
    app.route = 'load';

    // We include fetch.js polyfill in route.html for simplicity
    // 1. bower install fetch
    // 2. Add <script src="../../bower_components/fetch/fetch.js"></script> to routing.html
    fetch('/pages/test.html')
      .then(function(response) {
        return response.text()
      }).then(function(body) {
        document.querySelector('#load').innerHTML = body;
      });
  });

  ...

We could then implement any amount of pages we want in routing.html that would load our html pages as needed.

Note, this basic approach doesn't take into account caching the response (back/forward would trigger the request again, which you probably don't want from a performance standpoint) and we're not catching our errors in the above example. But it's one such approach.

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