简体   繁体   中英

Preload page into turbolinks transition cache

I'm using turbolinks to simulate a "single-page" app. The app is acceptably quick once pages are cached, however the first clicks are too slow. Is there a way to pre-fill the transition cache by loading some pages in the background?

I'm going to be looking into hacking into the page cache, but wondering if anyone has done this before.

(If this seems unusual, well, just trust that I'm doing this for good reason. Turbolinks gets nearly the performance of a far more complex implementation and overall I'm quite happy with it.)

UPDATE: So it seems like this SHOULD be relatively easy by simply adding entries to the pageCache of Turbolinks, something like:

$.ajax({
  url: url,
  dataType: 'html',
  success: function(data) {
    var dom = $(data);
    Turbolinks.pageCache[url] = {
      ...
    }
  }
});

however it doesn't seem possible to construct a body element in javascript, which is required. Without out that, it doesn't seem like I can't construct the object that is stored in the cache without the browser first rendering it.

Any ideas beyond hacking more into Turbolinks?

UPDATE 2: There was the further problem that pageCache is hidden by a closure, so hacking Turbolinks is necessary. I have a solution that I'm testing that leverages iFrames - seems to be working.

First Hack Turbolinks to allow access to pageCache, the end of your turbolinks.js.coffee should look like this.

@Turbolinks = {
  visit,
  pagesCached,
  pageCache,
  enableTransitionCache,
  enableProgressBar,
  allowLinkExtensions: Link.allowExtensions,
  supported: browserSupportsTurbolinks,
  EVENTS: clone(EVENTS)
}

Then implement a fetch function. This is what you were thinking about, we can use DOMParser to convert string into DOM object.

function preFetch(url) {
        $.ajax({
            url: url,
            dataType: 'html'
        }).done(function(data) {
            var key = App.Helper.getCurrentDomain() + url;
            var parser = new DOMParser();
            var doc = parser.parseFromString(data, "text/html");
            Turbolinks.pageCache[key] = {
                url: url,
                body: doc.body,
                title: doc.title,
                positionY: window.pageYOffset,
                positionX: window.pageXOffset,
                cachedAt: new Date().getTime(),
                transitionCacheDisabled: doc.querySelector('[data-no-transition-cache]') != null
            };
        });
    };

Usage:

$(function() {
    preFetch('/link1'); // fetch link1 into transition cache
    preFetch('/link2'); // fetch link2 into transition cache
});

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