Search code examples
angularjsprerender

How to get Prerender.io to recognize a unique page when it does not have a route explicitly set?


I plan on using Prerender.io to turn my SPA (built with AngularJS) into a collection of cached pages. The app/website is multilanguage (English and French) and I'm using Angular Dynamic Locale to handle the language switching. Unlike a menu item, a language link in the switcher doesn't contain an href with route path but is bound to a controller that basically updates a variable and reloads the route.

My question is this: How to get Prerender.io to recognize a unique page when it does not have a route explicitly set? Of course my aim is to have the French version of each page cached separately.

Currently I am setting a query parameter in the controller attached to the language switcher (see snippets below). This is triggered by a function on ng-click. Will Prerender.io pick that up as a separate page?

(It is my understanding that Prerender.io does treat a route/path with a query parameter as a separate page unless told to explicitly ignore it; my question is more about whether setting the parameter in the controller rather than in the anchor tag might change things.)

Here's the template mark-up for the language switcher:

<nav class="lang-switcher" ng-controller="LanguageCtrl">
  <a href ng-click="changeLanguage('en')" ng-class="{current: language == 'en'}">English</a>
  <a href ng-click="changeLanguage('fr_FR')" ng-class="{current: language == 'fr_FR'}">Français</a>
</nav>

The controller (I've removed the code that's not relevant to the question):

.controller('LanguageCtrl', ['$scope', '$route', '$location', function ($scope, $route, $location) {

  $scope.changeLanguage = function(lang) {

    // Do some stuff.

    // If the page is in French, attach query parameter to the URL.
    $location.path($location.path()).search({'lang': ( lang == 'fr_FR' ? 'fr' : null )});

    $route.reload();
  };
}])

Of course then the problem becomes what happens to the switcher links once the page is cached as static. But one hurdle at at time... :)

Thanks in advance!


Solution

  • Crawlers don't click links so you'll want to populate the href tag there. That way they crawlers will parse the link and then make another request to the different link.

    <nav class="lang-switcher" ng-controller="LanguageCtrl">
      <a href="/path?lang=en" ng-click="changeLanguage('en')" ng-class="{current: language == 'en'}">English</a>
      <a href="/path?lang=fr" ng-click="changeLanguage('fr_FR')" ng-class="{current: language == 'fr_FR'}">Français</a>
    </nav>
    

    You are correct that Prerender.io will cache a URL separately with a different query parameter if you don't tell Prerender.io to ignore it.