简体   繁体   中英

Lazy-Loading 3rd Party Service?

There's a help service that I can load by putting this at the bottom of the body section on my home page:

<script async type="text/javascript">
    !function (e, t, n) {
        function a() {
            var e = t.getElementsByTagName("script")[0], n = t.createElement("script");
            n.type = "text/javascript", n.async = !0, n.src = "https://beacon-v2.helpscout.net", e.parentNode.insertBefore(n, e)
        }

        if (e.Beacon = n = function (t, n, a) {
            e.Beacon.readyQueue.push({method: t, options: n, data: a})
        }, n.readyQueue = [], "complete" === t.readyState) return a();
        e.attachEvent ? e.attachEvent("onload", a) : e.addEventListener("load", a, !1)
    }(window, document, window.Beacon || function () {
    });
</script>

But loading it that way slows initial page load time and lowers my Lighthouse score.

I'd like to wait until my page has finished loading before calling this code.

Is it possible to get the same code to run inside of a React useEffect() ?

I set up a useInterval() to call this code after the initial page load is complete:

// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
useInterval(() => {
    loadHelpChat();
}, 2000);
function loadHelpChat(){
    if (typeof(Beacon) !== "undefined") return;
    !function (e, t, n) {
        function a() {
            var e = t.getElementsByTagName("script")[0], n = t.createElement("script");
            n.type = "text/javascript", n.async = !0, n.src = "https://beacon-v2.helpscout.net", e.parentNode.insertBefore(n, e)
        }

        if (e.Beacon = n = function (t, n, a) {
            e.Beacon.readyQueue.push({method: t, options: n, data: a})
        }, n.readyQueue = [], "complete" === t.readyState) return a();
        e.attachEvent ? e.attachEvent("onload", a) : e.addEventListener("load", a, !1)
    }(window, document, window.Beacon || function () {
    });
}

It seems like delaying the load by 2 seconds (that's the 2000 param sent to useInterval() ) convinces Lighthouse that loadHelpChat() should not be considered part of the initial page load.

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