Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 531
dtar Avatar asked Nov 26 '19 09:11

dtar


1 Answers

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
    };
};
like image 116
Dima Vishnyakov Avatar answered Nov 01 '22 06:11

Dima Vishnyakov