使用第三方插件導(dǎo)致Google PageSpeed Insights 評(píng)分過(guò)低

公司的文章頁(yè)面使用google PageSpeed Insights 分析過(guò)后渤昌,在移動(dòng)端的表現(xiàn)分?jǐn)?shù)很低愁铺,經(jīng)過(guò)其分析余素,結(jié)果如下


分析結(jié)果只有不到50分

從google分析給出的優(yōu)化建議上來(lái)看奔穿,關(guān)鍵原因在于頁(yè)面中使用了第3方y(tǒng)outube視頻播放插件阻塞了頁(yè)面的加載加載進(jìn)程

關(guān)鍵原因

google官方也給出了相關(guān)的解釋Loading Third-Party JavaScript 以下是部分摘錄

Loading Third-Party JavaScript

Third-party scripts provide a wide range of useful functionality, making the web more dynamic, interactive, and interconnected. These scripts may be crucial to your website's functionality or revenue stream. But third-party scripts also come with many risks that should be taken into consideration to minimize their impact while still providing value.

Why do you need to be careful about third-party scripts?

  • They can be a performance concern
  • They can be a privacy concern
  • They might be a security concern
  • They can be unpredictable and change without you knowing
  • They can have unintended consequences

Ideally, you’ll want to ensure third-party script is not impacting the critical rendering path. In this guide, we’ll walk through how to find and fix issues related to loading third-party JavaScript.

What do we mean by third-party scripts?

Third-party JavaScript often refers to scripts that can be embedded into any site directly from a third-party vendor. These scripts can include ads, analytics, widgets and other scripts that make the web more dynamic and interactive.

Examples of third-party scripts include:

  • Social sharing buttons (e.g Twitter, Facebook, G+)
  • Video player embeds (e.g YouTube, Vimeo)
  • Advertising iframes
  • Analytics & metrics scripts
  • A/B testing scripts for experiments
  • Helper libraries (e.g date formatting, animation, functional libraries etc)
youtube視頻播放器元素

One example of this is the YouTube video player embed script that allows you to embed a video into your page.

Unfortunately, embedding third-party scripts means we often rely on them to be fast in order to avoid slowing our pages down. Third-party scripts are a predominant cause of performance slowdowns and are often caused by resources outside of your control.

These issues can include:

  • Firing too many network requests to multiple servers. The more requests a site has to make, the longer it can take to load.

  • Sending too much JavaScript that keeps the main thread busy. Too much JavaScript can block DOM construction, delaying how quickly pages can render. CPU-intensive script parsing and execution can delay user interaction and cause battery drain.

  • Sending large, unoptimized image files or videos. This can consume data and cost users money.

  • Third-party scripts loaded without care can be a single-point of failure (SPOF)

  • Insufficient HTTP caching, forcing resources to be fetched from the network often

  • Lack of sufficient server compression of resources

  • Blocking content display until they complete processing. This can also be true for async A/B testing scripts.

  • Use of legacy APIs (e.g document.write()) known to be harmful to the user experience

  • Excessive DOM elements or expensive CSS selectors.

  • Including multiple third party embeds can lead to multiple frameworks and libraries being pulled in several times. This is wasteful and exacerbates the performance issues.

  • Third-party scripts often use embed techniques that can block window.onload if their servers respond slowly, even if the embed is using async or defer.

Context is important and the solution to costly third-parties can depend on your site and ability to configure how third-party code is being loaded. Thankfully a number of solutions and tools exist to find and fix issues with third party resources.

How do you load third-party script efficiently?

If a third-party script is slowing down your page load, you have several options to improve performance:

  • Load the script using the async or defer attribute to avoid blocking document parsing.

  • Consider self-hosting the script if the third-party server is slow.

  • Consider removing the script if it doesn't add clear value to your site.

  • Consider Resource Hints like <link rel=preconnect> or <link rel=dns-prefetch> to perform a DNS lookup for domains hosting third-party scripts.

Use async or defer

JavaScript execution is parser blocking. This means when the browser encounters a script it must pause DOM construction, hand this over to the JavaScript engine and allow script execution before proceeding with DOM construction.

The async and defer attributes change this behavior.

  • With async, the browser downloads the script asynchronously while it continues to parse the HTML document. When the script finishes downloading, parsing is blocked while the script executes.

  • With defer, the browser downloads the script asynchronously while it continues to parse the HTML document. The script doesn't run until the parsing is complete.

If that's too many words, here's a pretty picture:


image.png

In general, you should always use async or defer for third party scripts (unless the script does something necessary for the critical rendering path):

Use async if it's important to have the script run earlier in the loading process. This might include some analytics scripts, for example.

Use defer for less critical resources. A video player that's below-the-fold, for example.

Note: If performance is your primary concern, you could wait until your page has reached a key user moment (such as after the critical content has loaded) before adding async scripts. You should also take care not to async load libraries like jQuery just because they are coming from a third-party CDN.

Note: In Blink-based browsers, async and defer currently lower the priority of the network request for resources so it can cause it to load significantly later than it would as a blocking script. This is useful to know in particular for analytics scripts.

Should you ever load third-party scripts without async or defer? You could make a case for this if the script is a crucial part of your site functionality. For example, if you're loading your main UI library or framework from a CDN, it will be badged as "third-party script" in DevTools, but should be treated as an essential part of your site, not an add-on.

Note that not all scripts work if loaded asynchronously. Check the docs for any third-party scripts you're using. If you're using a script that can't be loaded asynchronously, you might want to consider an alternative, or eliminating the script if possible. Some third parties may highly recommend to load their scripts sync (to get ahead of other scripts), even if they would work fine async so do due diligence when evaluating strategies for loading third-party scripts.

Note: async is not a silver bullet. If a marketing team wants to load a large number of tracking scripts on a page, this number will still introduce bottlenecks that can impact how soon users can engage with a page on load.

Use Resource Hints to reduce connection setup time

Establishing connections to third-party origins can take a significant amount of time - particularly on slow networks. Many steps can add up to delays including DNS lookups, redirects, and potentially several round trips to each third-party server to handle the request.

You can use Resource Hints like to perform a DNS lookup for domains hosting third-party scripts. When the request for them is finally made, time can be saved as the DNS lookup has already been carried out.

<link rel="dns-prefetch" >

If the third-party domain you are referencing uses HTTPS, you may also consider as this will both perform the DNS lookup and resolve TCP round-trips and handle TLS negotiations. These other steps can be very slow as they involve looking at SSL certificates for verification, so consider Resource Hints seriously if you find third-party setup time to be an issue.

<link rel="preconnect" >

"Sandbox" scripts with an iframe

There are cases where third-party scripts can be loaded directly into an iframe. By restricting such scripts to iframes, they won’t block execution of the main page. This is the same approach that AMP takes to keeping JavaScript out of the critical path. Note that this approach will still block the onload event so try not to attach critical functionality to onload.

Note: Chrome is also exploring support for Feature Policy - a set of policies allowing a developer to selectively disable access to certain browser features. This can prevent third-party content introducing unwanted behaviors to a site.

Lazy-load Third Party Resources

Embedded third-party resources (such as ads or videos) can be a big contributor to slow page speed when constructed poorly. Lazy-loading can be used to only load embedded resources when necessary. For example, serving an ad in the footer only when a user scrolls down the page. Another pattern is lazy-loading content after the main page content loads but before a user might otherwise interact with the page.


lazyLoad

Note: LazySizes is a popular JavaScript library for lazy-loading images and iframes. It supports YouTube embeds and widgets. Care does need to be taken when lazy-loading any resources as this technique is often powered by JavaScript and can be subject to issues on flaky network connections.

DoubleClick have guidance on how to lazy-load ads in their official documentation. If used properly, lazy loading can increase the overall viewability percentage of an ad. For example, Mediavine switched to lazy-loading ads and saw a 200% improvement in page load speed.

Efficient lazy-loading with Intersection Observer

Historically, solutions for detecting if an element is visible in the viewport (in order to lazy-load its content) have been error-prone, often causing the browser to become sluggish. Solutions have often listened for scroll or resize events, then used DOM APIs like getBoundingClientRect() to calculate where elements are relative to the viewport. This works, but is not efficient.

IntersectionObserver is a browser API that allows us to efficiently detect when an observed element enters or exits the browser's viewport. Learn more about how to use it for lazy-loading resources. LazySizes also has optional support for IntersectionObserver.

最后

Youtube視頻插件處理

我們文章頁(yè)使用了iframe引入youtube視頻镜沽,采用延遲加載的方案,一開(kāi)始iframe的src為空贱田,頁(yè)面加載完后再給iframe的src賦值視頻地址即可缅茉。facebook插件也是同樣的處理方案

 <iframe width="640" height="360" yt-src="https://www.youtube.com/embed/Pl0t2Kz-ccY" frameborder="0"
                  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                  allowfullscreen>
 </iframe>
 $(function() {
// 定時(shí)器防止進(jìn)程阻塞
        setTimeout(function() {
            // facebook like plugin Delay loading to prevent blocking process
            $.fbLike()
            var yturl = $("iframe[yt-src]").attr("yt-src")
            // youtube video   Delay loading to prevent blocking process
            $("iframe[yt-src]").attr("src", yturl)
        }, 3000)
    })
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市男摧,隨后出現(xiàn)的幾起案子蔬墩,更是在濱河造成了極大的恐慌,老刑警劉巖耗拓,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拇颅,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡乔询,警方通過(guò)查閱死者的電腦和手機(jī)樟插,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)哥谷,“玉大人岸夯,你說(shuō)我怎么就攤上這事麻献∶峭祝” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵勉吻,是天一觀的道長(zhǎng)监婶。 經(jīng)常有香客問(wèn)我,道長(zhǎng)齿桃,這世上最難降的妖魔是什么惑惶? 我笑而不...
    開(kāi)封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮短纵,結(jié)果婚禮上带污,老公的妹妹穿的比我還像新娘。我一直安慰自己香到,他們只是感情好鱼冀,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布报破。 她就那樣靜靜地躺著,像睡著了一般千绪。 火紅的嫁衣襯著肌膚如雪充易。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天荸型,我揣著相機(jī)與錄音盹靴,去河邊找鬼。 笑死瑞妇,一個(gè)胖子當(dāng)著我的面吹牛稿静,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播辕狰,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼自赔,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了柳琢?” 一聲冷哼從身側(cè)響起绍妨,我...
    開(kāi)封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎柬脸,沒(méi)想到半個(gè)月后他去,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡倒堕,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年灾测,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片垦巴。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡媳搪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出骤宣,到底是詐尸還是另有隱情秦爆,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布憔披,位于F島的核電站等限,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏芬膝。R本人自食惡果不足惜望门,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望锰霜。 院中可真熱鬧筹误,春花似錦、人聲如沸癣缅。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至丽惶,卻和暖如春炫七,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背钾唬。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工万哪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人抡秆。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓奕巍,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親儒士。 傳聞我的和親對(duì)象是個(gè)殘疾皇子的止,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容