VueJS: Xây dựng một SPA thân thiện với Vue.js với Prerender & các mẹo khác

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Nếu không có thời gian tìm hiểu, bạn có thể xem bài viết Prerender với vue-spa-plugin v3.

Do you know about the defeat story of Hulu?

Back to 2016, Online video service was down 56% posibility display because bad JS processing.

This was a bad practise that no company wants to have.

If you don't want to see that problem, you must know what to do with modern JavaScript framework.

We like Vue.js, but we know problems with SEO of Vue.js single page.

At this tutorial, I want to show developers how easy friendly with SEO of Vue.

We will discuss:

  • Common SEO advice you should always to use.
  • Specified problems with SEO Vue.js.
  • Tools to maintain them with server render and prerender.
  • An example with SEO technical for Vue.js using prerender-spa-plugin.

This is the full update of SEO Vue.js resources of us. The official is followed by two parts is about SEO of JS framework for React and Angular. In addition, we have a version of this content that you can find at the end of this article.

Summary SEO trends

Before we discovery SEO problems with JavaScript SPA, wrapping the best practice developers should apply when building webpages that optimize for SEO.

As someone said: "The best position to hide the dead is the second page of Google Search"

This minify list is summary from some best SEOers as Moz, Backlinko, and Ahrefs. I added links to resources of them if you want to deep learning.

→ meta tag?️

Meta tag is the low fruids. They allow you render accurate search tools what your content is.

However, every thing is not same. You only focus your energy to some of them, as:

  • Content type, meta is show on every page, declare your characters set for page.
  • Title, select a good title for atractive the notice of searcher while description accurate content page. Keep it sort and optimize!
  • Meta description, use to description for user SERP (Search Engine Result Page) click to your link to find the answer they want.
  • Viewport, essential for google mobile experence.

Learn more: SEO Meta Tags, by Moz.

vue-meta is the good plugin to manage meta information of page in Vue 2.0 components.

Social tags also can eficient to SEO because they support transfer your content on social platform, so it increasing your SEO social. There are specified tags for major platform (Facebook, Twitter, Pinterest, Google+).

Learn more: Must has social meta tag for Twitter, Google+, Facebook and more, by Moz.

→ Mobile optimize

If you don't know about the first index create on mobile ofGoogle, this is an alert! Google current spending more focus for experience smooth mobile than desktop and you too.

Learn more: mobile SEO: complete tutorial, by Backlinko.

NativeScript supporting mobile app Vue.js more levels.

→ HTTPS

HTTPS Certificate was lost or error config can make your website is so bad. After all of the thing, Search tools will increase good websites and certificated?

Even you don't care SEO, you also can want to provide the most security platform for your clients. So, no problem no caring this item!

Learn more: HTTP vesus HTTPS with SEO: things you know for maintain good status of Google by ahrefs.

→ Page speed

The notice of everyone is sort searching to fast abort slow load page. Google know that to provide the best UX for searcher, it will escape slow pages.

Googlebots self does not care and does not wait statements 5 seconds longer. If you don't response this waiting time, you could not full display of your content. Speedup!

Learn more: offpage SEO: page speed, of Moz.

→ Sitemap website

Sitemap website working as your website's sitemap of searching. It included pages that you think those are target & good quality navigate, should for indexing.

With smaller websites, they maybe not benefit, but you still apply SEO tool for them.

Learn more: XML sitemap: The most misunderstood tool in tool box of SEO, by Moz.

You can create a sitemap.xml with vue-router config.

→ Links build

Building your domain authority is still an important strategy of SEO. How to Google knowes that you were became an authority resource? By you have other related domains link to your website.

There is no security way in here, to perform this, you need to try creating a good content. This content must is good for other people want to share and using as resource on their websites.!

When you receivd more and more links from related sources, then your permision will increase, and you will receivd more and more Google's fift when ranking.

Learn more: Links building for SEO: Definitive tutorial, by Backlinko.

Specific Vue.js SEO problems

vue-js-seo-demo

For the following tutorial, I decided using the blog demo that we performed in previous article because of in fact that it was very worldefull. If you want to know how it built, see this article.

Inspide of that is an wonderfull article with real view, but with SEO it was not good setup. That was a completed SPA that searching tool became difficult when crawlering data and indexing.

Why?

A SPA will auto add content to pages, this action has some benefits, but generates two important problems:

  1. We infact do not know that Google can collect data and display accurate level of Google. They said in some years that Googlebots can do that. However, this statements always to following by one or two "but".
  2. Google is not only search tool. If every thing stills not already, we know that infact other players not crawler info about JS, so it was not see the infact content of page.

So, there is no way around it. If you want to make sure that your websites/apps of Vue.js are rating on SERPs, you must action follow it.

Your options?

Server Rendering

With SSR setup, you have rendering logic that live performed in helper in Node.js. HTML views then return for customer, already serve for bot searching.

It is wonderfull for timing sensing applications, where you want to reduce logic as well as on server, but it with cost. You will need a strong base to process stresses added server, require more time for develop. You can also slowdown your system while developing.

 

But if you can process it, that already the way for bigger application. No doubt, Nuxt.js is a tool for your Vue.js SPA servered renderer.

 

Quá trình kết xuất Nuxt.js

Prerequisite

However, sometimes, server rendering can be overkill, as my demo. With a small SPA has only some pages, no difficult with SEO.

With this way, you do not need attact your Vue.js app with any server. Rendering is executed by client side with using plugins of third party, for example:

  • Prerender.io - Matching with all of the most JS frameworks, included Vue.js.
  • prerender-spa-plugin - An webpack plugin will compile your pages to static pages. It is very easy to index and make all of contents exists in resource.

prerender-spa-plugin is very easy to use and built by a member of Vue.js core team, so it absolutely match with us for using here.

Example how to SEO of Vue.js by using prerendering

vue-js-seo-prerender-demo

Dành thời gian để sửa chữa lại prerender blog Vue.js. Với việc sử dụng plugin prerender-spa-plugin, tôi sẽ có một Vue.js SPA với chỉ định lợi ích của Google ngay bây giờ.

Điều kiện tiên quyết

  • Kiến thức cơ bản về Vue.js
  • Thiết lập Node.js & npm

1. Cài đặt prerender-spa-plugin

Cấu hình plugin rất dễ dàng. Trong thiết lập này, tôi chỉ chạy plugin khi xây dựng bản production. Bạn không cần phải trình bày trước khi phát triển các thành phần hoạt động.

Bắt đầu bằng cách cài đặt plugin từ npm.

npm install prerender-spa-plugin

 

Tiếp theo mở file build/build.js. Trong đó, bạn sẽ tìm thấy các tùy chọn để xây dựng bản production. Bạn sẽ cần phải nhập plugin và thêm các câu lệnh này ở đầu file:

// /build/build.js
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;

Sao lại sử dụng PrerenderSPAPlugin.PuppeteerRenderer? Bởi vì bạn sẽ cần trình kết xuất tùy chỉnh. Bạn cần phải tiêm một số dữ liệu cho ứng dụng biết khi nào nó được đăng ký trước. Có một số điều như nhận xét về Disqus mà bạn không thể đăng ký trước.

Với một ứng dụng tự do với SEO 100%, tốt hơn là bạn nên có lợi ích từ những bình luận này vì nội dung được hiển thị trên các trang của bạn. Nếu bạn làm việc với người dẫn trang tĩnh, bạn nên sử dụng Tĩnh cho nội dung mà người dùng đã tạo.

Bạn sẽ cần tìm nạp tất cả blog và tạo danh sách các route sẽ trình bày trước. Trong thực tế với tập lệnh sản xuất, hãy giúp bạn muốn gọi API CMS mà không có tiêu đề của bạn hoặc một máy chủ bên ngoài bảo vệ nội dung của bạn. Trong trường hợp này, dữ liệu sẽ sống trong các tệp JSON đơn giản.

Đọc file feed.json và tạo các route:

// /build/build.js

const fileContent = fs.readFileSync(path.resolve(__dirname, '..', 'static', 'api', 'feed.json'));
const feed = JSON.parse(fileContent);
const prenderedRoutes = feed.results.map(x => `/read/${x.id}`);

prenderedRoutes.unshift('/');

Thêm plugin vào cấu hình webpack:

// /build/build.js

webpackConfig.plugins.push(
  new PrerenderSPAPlugin({
    staticDir: path.resolve(__dirname, '..', 'dist'),
    routes: prenderedRoutes,
    renderer: new Renderer({
      injectProperty: '__PRERENDER_INJECTED',
      inject: {
        prerendered: true
      },
      renderAfterDocumentEvent: 'app.rendered'
    })
  }));

You can access in variable window.__PRERENDER_INJECTED.prerendered when the page is not ready. This will very useful for subtract content that you do not want prerender.

You also need specify waiting for app.rendered event.

In this demo, I will use Pace, this is a good library for fast add progresser on a page. However, you need to make sure that loading progress must finish before register page, else you will received a random progress on multi page.

2. Config Vue.js for prerender

Then, you will need apply some small change in some components. To do this, I changed how Pace was started. I escaped file startup.cs and set everything in main.js.

Open file main.js and change App included your components:

// /main.js

new Vue({
  router,
  render: h => h(App),
  mounted() {
    Pace.start()
    Pace.on('hide', () => {
      document.dispatchEvent(new Event('app.rendered'));
    })
  }
}).$mount('#app')

When main component is mounted, starting Pace and sending event app.rendered when start loading is over.

The last updated you must do that you make sure Disqus is loaded while webpage is being prepared.

Open file BlogPost.vue you will include Disqus component.

Since start config with prerender-spa-plugin, you could access a variable know that website is pre-registerd.

Update method showComments as follow:

// /BlogPost.vue

showComments() {
    // This is injected by prerender-spa-plugin on build time, we don't prerender disqus comments.
    if (window.__PRERENDER_INJECTED &&
        window.__PRERENDER_INJECTED.prerendered) {
      return;
    }
    setTimeout(() => {
      this.commentsReady = true
    }, 1000)
}

3. Build Vue.js website friendly with SEO

Now you are ready building your website. In terminal you use this statement:

npm run build

Then, if you look at dist folder dist, you will see all articles in read folde. A static HTML file created for every article:

thư mục xa

Live demo, Github repo & video tutorial

View live demo at here

View repo GitHub at here

Represent vission about this content:

Reduce thought

prerender-spa-plugin is an optimal plugin. It's easy to config and flexible enought to process syns using cases as we had Pace.

I spent about 2 hours found connect all of these together and update our start app to support prerender.

As I mentioned earlier, plugin is very simple and matching with simple application as static blog. If you want to build some thing more complex, I recomment you should use Nuxt!

» Tiếp: vue-meta full
« Trước: Vấn đề SEO với Vue.js
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!