简体   繁体   中英

How to run code (Google/Doubleclick Ads) without block main thread

Is there any way to run Google Ads code without block main thread? Google Pagespeed Insights shows me a warning "Reduce the impact of third-party code" : Third-party code blocked the main thread for ...

Third-Party                   Size         Main-Thread Blocking Time
Google/Doubleclick Ads        193 KB       253 ms

I've placed a script to the end of the page in the footer.

<script data-ad-client="ca-pub-xxx" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

I tried to add "data-aload data-original=..." but it doesn't help. Maybe it would a right choice to use requestAnimationFrame() or setTimeOut(), but I don't know how to implement it on this.

You can add script dynamically. NB there is no need to add async since browser considers all dynamic script async by default

const loadScript = (src, id, callback) => {
    const script = document.createElement('script');
    script.src = src; // URL for the third-party library being loaded.
    script.id = id; // e.g., googleMaps or stripe
    script.defer = true; // make sure that browser will run script after page loaded
    document.body.appendChild(script);

    script.onload = () => {
      if (callback) callback(); // conditional callback
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM