How to achieve SEO in AngularJS SPA

2020-05-24 10:06发布

问题:

After going through some existing question and it's answers, I am not able to come perfect strategy to be followed to achieve SEO in AngularJs.

Ways I Found to achieve it are-

  1. Create Nginx intermediate layer that will serve crawlers request with differently.

  2. Convert AngularJS application to support HTML5 mode. But it's only supported by Google(Using WebMaster Tool) search engine.

  3. Use paid tools available to support SEO in AngularJS like brombone, prerender, getseojs

I need help to choose this alternatives and it will be beneficial for my 1 to 20 AngularJS (SAP). I have already gone through this stack question

回答1:

As the linked stack questions says

"Google crawlers now executes javascript - you can use the Google Webmaster Tools to better understand how your sites are rendered by Google." Check it out here

That means you don't need to go through a lot of the painful steps to get Google to index the AJAX loaded HTML. If you load the meta-data in with AJAX you will be fine.

A solution that I have made was to create a AngularJS directive to quickly add the meta data and title name of the page from the model which is loaded.

  /*
  SEO directives
   */

  dtvs.directive('metaSeo', function() {
    return {
      restrict: 'E',
      scope: {
        desc: '=',
        title: '='
      },
      link: function(scope, el, attr) {
        scope.$watch('desc', function() {
          return $("head meta[name='description']").attr('content', scope.desc);
        });
        return scope.$watch('title', function() {
          return $("head title").html(scope.title);
        });
      }
    };
  });

I've used jQuery to do that in the above example, but feel free to swap that out.

The above directive gives you an HTML element you can just place somewhere on that page:

<meta-seo data-desc="lesson.brief" data-title="lesson.title"></meta-desc>

If you have a similar directive then the SEO metadata and title should be crawled by google without problem.