Backbone routing/history issue with Jekyll static pages

梦想的初衷 提交于 2019-12-08 03:49:13

问题


I'm building a simple marketing website with Jekyll, and using Backbone's routing and history behind the scenes to handle navigation. Each page of my site is its own HTML file, and my strategy is to preventDefault() on links between pages, fire off a jQuery.get() to grab the new HTML, and replace my div.content with the information from the new page.

I know this setup is a little out of the ordinary, but I have my reasons: a single-page structure is preferable because I want precise control over page transitions, and I want to avoid requesting my webfonts each time the user navigates to a new page. Keeping the HTML files static and separate is also a win for search engines.

Here's the issue: everything works fine when I start from my root URL, but when I begin at a different page, e.g. mydomain.com/page1, the history breaks. During initialization, my Router attempts to route me to the page I'm already on, resulting in a 404: Could not GET mydomain.com/page1/page1. I can prevent this with a hacky isFirstLoad boolean, but that obviously sucks, and it doesn't breaks when I start clicking around and use the back button to return to /page1.

I recognize that one solution is to write some server-side logic that serves my index.html regardless of what URL is hit. I'm not sure how to do this, however, particularly for a local environment. Is it about PHP or .htaccess? Is this even what I have to do? Am I going about this totally the wrong way?

Thanks!


回答1:


Yes, one solution would be to serve every request with index.html. But that has a big downside: your site is no longer accessible by search engines. To keep the SEO benefit of having a static site, I'd suggest you shy away from that option.

I think the optimal solution is already provided by Backbone. From their documentation:

If the server has already rendered the entire page, and you don't want the initial route to trigger when starting History, pass silent: true.

So, first make sure that your Router is configured properly and all the routes match up with your static pages, and instantiate the router.

Then, start the History like this:

Backbone.history.start({ pushState: true, silent: true, root: '/' });

Push State will help keep the URLs friendly. The Silent flag tells Backbone that your static server served the page already, and it's just loading in after the fact (what you want). And the Root configuration ensures that Backbone knows what the true root of your site is (so you don't get the page1/page1 nonsense.

In my experience, getting routing set up properly can be a little fickle...so best of luck!



来源:https://stackoverflow.com/questions/24559179/backbone-routing-history-issue-with-jekyll-static-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!