Four schemes of Vue SEO

Posted by BigJohn on Thu, 09 Dec 2021 06:35:45 +0100

As we all know, Vue SPA single page application is not friendly to SEO. Of course, there are corresponding solutions. There are probably the following four methods by looking up data. (I have only used the first and third schemes)

1.Nuxt server rendering application deployment (SSR server rendering)

About server rendering: introduction to Vue official website. There are requirements for Vue version and server. nodejs environment needs to be supported.

Where SSR trade-offs are used:

Limited by development conditions, browser specific code can only be used in some life cycle hook functions; Some external libraries may require special processing to run in server rendering applications;
The environment and deployment requirements are higher, and the Node.js server running environment is required;
In case of high traffic, please prepare the corresponding server load and adopt caching strategy wisely.

Advantages:

Better SEO, because the search engine crawler can directly view the fully rendered page; Faster time to content, especially for slow network conditions or slow devices.

Deficiency: (pit encountered in development)

1. One set of code and two sets of execution environments will cause various problems. For example, the server does not have window and document objects. The processing method is to add judgment. If it is executed by the client:

if(process.browser){
 console.log(window);
}
Copy code

Reference npm package, with dom operation, for example: wowjs, can not be import ed, but instead:

if (process.browser) {
  var { WOW } = require('wowjs');
  require('wowjs/css/libs/animate.css');
 }
Copy code

2. The nuxt asyncdata method obtains data before initializing the page, but is limited to page component calls:

// Concurrent loading of multiple interfaces:
 async asyncData ({ app, query }) {
 let [resA, resB, resC] = await Promise.all([
  app.$axios.get('/api/a'),
  app.$axios.get('/api/b'),
  app.$axios.get('/api/c'),
  ])
   
  return {
  dataA: resA.data,
  dataB: resB.data,
  dataC: resC.data,
  }
 }
Copy code

3. If you use v-if syntax, you will probably encounter this error when deploying online:

Error while initializing app DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method. at Object.We [as appendChild] according to the prompt in issue 1552 on github nuxt, change v-if to v-show syntax.

2.Nuxt static application deployment

When Nuxt.js performs generate static packaging, dynamic routing will be ignored.

-| pages/
---| index.vue
---| users/
-----| _id.vue
Copy code

Dynamic routing is required to form a static page. You need to specify the value of dynamic routing parameters and configure them in the routes array.

// nuxt.config.js
module.exports = {
 generate: {
 routes: [
  '/users/1',
  '/users/2',
  '/users/3'
 ]
 }
}
Copy code

Run packaging, and you can see the packaged page.

But what should I do if the value of routing dynamic parameters is dynamic rather than fixed?

Use a function that returns Promise object type; Using a callback is a function of callback(err, params).

// nuxt.config.js
import axios from 'axios'
 
export default {
 generate: {
 routes: function () {
  return axios.get('https://my-api/users')
  .then((res) => {
  return res.data.map((user) => {
   return {
   route: '/users/' + user.id,
   payload: user
   }
  })
  })
 }
 }
}
Copy code

Now we can start from / users/_ The payload accessed by id.vue is as follows:

async asyncData ({ params, error, payload }) {
 if (payload) return { user: payload }
 else return { user: await backend.fetchUser(params.id) }
}
Copy code

If your dynamic routing has many parameters, such as product details, it may be as high as tens of thousands. You need an interface to return all IDS, and then traverse the IDS during packaging and package locally. If a commodity is modified or off the shelf, it has to be repackaged. In case of a large number, the packaging is also very slow and unrealistic.

Advantages:

Pure static file, super fast access speed; Compared with SSR, server load is not involved; Static web pages should not be attacked by hackers, with higher security.

Insufficient:

Not applicable if there are many dynamic routing parameters.

3. Pre render spa plugin

If you only use it to improve the SEO of a few marketing pages (such as /, / about, /contact, etc.), you may need to pre render. Instead of using the web server to dynamically compile HTML in real time, the pre rendering method is used to simply generate static HTML files for specific routes at build time. The advantage is that it is easier to set up pre rendering, and you can use your front end as a completely static site.

1 $ cnpm install prerender-spa-plugin --save
vue cli 3 vue.config.js configuration:

const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
module.exports = {
 configureWebpack: config => {
  if (process.env.NODE_ENV !== 'production') return;
  return {
   plugins: [
    new PrerenderSPAPlugin({
     // The path of the generated file can also be consistent with that packaged by webpakc.
     // The following sentence is very important!!!
     // This directory can only have one level. If the directory level is greater than one level, there will be no error prompt during generation, and it will only be stuck during pre rendering.
     staticDir: path.join(__dirname,'dist'),
     // Corresponding to your own routing file, for example, if a has parameters, you need to write it as / a/param1.
     routes: ['/', '/product','/about'],
     // This is very important. If this section is not configured, it will not be precompiled
     renderer: new Renderer({
      inject: {
       foo: 'bar'
      },
      headless: false,
      // In main.js, document.dispatchevent (new event ('render event '), and the event names of the two should correspond to each other.
      renderAfterDocumentEvent: 'render-event'
     })
    }),
   ],
  };
 }
}
Copy code

Add in main.js:

new Vue({
 router,
 render: h => h(App),
 mounted () {
 document.dispatchEvent(new Event('render-event'))
 }
}).$mount('#app')
Copy code

Note: mode: "history" must be set in router.

You can see the file after packaging, and package the folder / index.html, for example: about = > about / index.html, which contains HTML content.

Advantages:

Small changes, the introduction of a plug-in is done;

Insufficient:

Cannot use dynamic routing; It is only applicable to projects with a small number of pages. When there are hundreds of pages, the packaging will be very slow;

4.Phantomjs deals with reptiles

Phantomjs is a headless browser based on webkit kernel, that is, it has no UI interface, that is, it is a browser, but the related operations such as clicking and page turning need to be programmed and implemented.

Although "phantom JS announced the termination of development", it has met the SEO processing of Vue.

This solution is actually a bypass mechanism. The principle is to determine whether the access source UA is a crawler access through Nginx configuration. If so, the crawler request of the search engine will be forwarded to a node server, and then the complete HTML will be parsed through phantom JS and returned to the crawler.

To install global phantomjs, local express, test:

$ phantomjs spider.js 'www.baidu.com 'if you see a push of html on the command line, congratulations. You have conquered PhantomJS.

After startup, or use postman to add the user agent value to the request header as Baiduspider, the effect is the same.

Deploy Online

node, pm2, phantomjs and nginx related configurations to be installed on the line:

upstream spider_server {
 server localhost:3000;
}
 
server {
 listen  80;
 server_name example.com;
  
 location / {
  proxy_set_header Host   $host:$proxy_port;
  proxy_set_header X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 
  if ($http_user_agent ~* "Baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|bingbot|Sosospider|Sogou Pic Spider|Googlebot|360Spider") {
  proxy_pass http://spider_server;
  }
 }
}
Copy code

Advantages:

There is no need to change the project code at all. It can be developed according to the original SPA. Compared with the development of SSR, the cost is small and not too much; For projects that have been developed with SPA, this is the best choice.

Insufficient:

node server support is required for deployment;
Crawler access is slower than web page access, because resources are returned to the crawler after loading regularly;
If it is maliciously simulated that Baidu crawlers crawl a large number of cycles, it will cause problems in server load. The solution is to judge whether the accessed IP is the IP of Baidu's official crawler.

summary

If you build large websites, such as shopping malls, don't hesitate to directly render on the SSR server. Of course, there are corresponding pits waiting for you. The community is more mature and English is better. All problems can be solved easily.

If it's just a personal blog or a company's official website, the other three are OK.

last

If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: http://github.crmeb.net/u/defu esteem it a favor  !