I have a problem with the time that it takes to lo...
# support
s
I have a problem with the time that it takes to load the Rudderstack Script. I set delayLoad = true, manualLoad to 8000 and it still loads in the first 1 second. I also set the script to defer and tried async but no difference. I’m running on Gatsby. Ideally I’d like to load it at the end of the page load not the beginning. I read somewhere it takes 60ms to download, I have it at over 1 second and that’s only sending a hit to GA4 at the moment.
g
can you please share the full js script snippet that you are using to load
s
I'm using the Gatsby plugin.
g
I see. I haven't used RudderStack gatsby plugin. Let me look into the docs
I see this comment for
manualLoad
// Whether to completely skip calling
analytics.load()
.
// ADVANCED FEATURE: only use if you are calling
analytics.load()
manually
// elsewhere in your code or are using a library
// that will call it for you.
// Useful for only loading the tracking script once a user has opted in to being tracked, for example.
// *Another use case is if you want to add callbacks to the methods at load time.
Can you try
manualLoad: false
s
It already is.
Would you like to see the whole config file?
g
yes please. and any other code related to rudderstack you have in your page
s
Copy code
// your rudderstack write key for your production environment
        // when process.env.NODE_ENV === 'production'
        // required; non-empty string
        //NOTE: Do not commit this to git. Process from env.
        prodKey: `my key`,
  
        // if you have a development env for your rudderstack account, paste that key here
        // when process.env.NODE_ENV === 'development'
        // optional; non-empty string
        //NOTE: Do not commit this to git. Process from env.
        devKey: `my key`,
  
        // boolean (defaults to false) on whether you want
        // to include analytics.page() automatically
        // if false, see below on how to track pageviews manually
        trackPage: true,
  
        // number (defaults to 50); time to wait after a route update before it should
        // track the page change, to implement this, make sure your `trackPage` property is set to `true`
        trackPageDelay: 50,
  
        // If you need to proxy events through a custom data plane,
        // add a `dataPlaneUrl` property (defaults to https://hosted.rudderlabs.com )
        // RudderStack docs:
        //   - https://docs.rudderstack.com/rudderstack-sdk-integration-guides/rudderstack-javascript-sdk#3-1-load
        // dataPlaneUrl: `https://override-rudderstack-endpoint`,
  
        // Add a `controlPlaneUrl` property if you are self-hosting the Control Plane
        // RudderStack docs:
        //   - https://docs.rudderstack.com/rudderstack-sdk-integration-guides/rudderstack-javascript-sdk#3-1-1-self-hosted-control-plane
        // controlPlaneUrl: `https://override-control-plane-url`,
  
        // boolean (defaults to false); whether to delay load RudderStack
        // ADVANCED FEATURE: only use if you leverage client-side routing (ie, Gatsby <Link>)
        // This feature will force RudderStack to load _after_ either a page routing change
        // or user scroll, or after `delayLoadTime` elapses, whichever comes first. This feature is used to help improve your website's
        // TTI (for SEO, UX, etc).  See links below for more info.
        // NOTE: But if you are using server-side routing and enable this feature,
        // RudderStack will never load (because although client-side routing does not do
        // a full page refresh, server-side routing does, thereby preventing RudderStack
        // from ever loading).
        // See here for more context:
        // GIF: https://github.com/benjaminhoffman/gatsby-plugin-segment/pull/19#issuecomment-559569483
        // TTI: https://github.com/GoogleChrome/lighthouse/blob/master/docs/scoring.md#performance
        // Problem/solution: https://marketingexamples.com/seo/performance
        delayLoad: true,
  
        // number (default to 1000); time to wait after the page loads
        // to load the RudderStack SDK
        // To be used when `delayLoad` is set to `true`
        delayLoadTime: 2500,
  
        // Whether to completely skip calling `analytics.load()`.
        // ADVANCED FEATURE: only use if you are calling `analytics.load()` manually
        // elsewhere in your code or are using a library
        // that will call it for you.
        // Useful for only loading the tracking script once a user has opted in to being tracked, for example.
        // *Another use case is if you want to add callbacks to the methods at load time.
        manualLoad: false,
  
        // string ('async' or 'defer'); whether to load the RudderStack SDK async or defer. Anything else
        // will load normally.
        // 'async' will load the SDK as <script async></script>
        // 'defer' will load the SDK as <script defer></script>
        loadType: 'default',
  
        // Options to the `load` API
        // Note: The above `controlPlaneUrl` overrides the `configUrl` field in this object
        // loadOptions: {
          
        // }
Only difference between the above config and my version online is currently the delayLoadTime = 8000 and the keys are live ones.
Also load type I changed to defer
this id the script output (in the header)
<script defer=“” src=“https://cdn.rudderlabs.com/v1/rudder-analytics.min.js”></script>
Copy code
window.rudderSnippetLoaded = false;
      window.rudderSnippetLoading = false;
      window.rudderSnippetLoadedCallback = undefined;
      window.rudderSnippetLoader = function (callback) {
        if (!window.rudderSnippetLoaded && !window.rudderSnippetLoading) {
          window.rudderSnippetLoading = true;
          function loader() {
            window.rudderanalytics.load('removed', 'https://hosted.rudderlabs.com');
            window.rudderSnippetLoading = false;
            window.rudderSnippetLoaded = true;
            if (callback) { callback(); }
            if (window.rudderSnippetLoadedCallback) {
              window.rudderSnippetLoadedCallback();
              window.rudderSnippetLoadedCallback = undefined;
            }
          };

          "requestIdleCallback" in window
            ? requestIdleCallback(function () { loader(); })
            : loader();
        }
      }
      window.addEventListener('scroll',function () {window.rudderSnippetLoader()}, { once: true });
      setTimeout(
        function () {
          "requestIdleCallback" in window
            ? requestIdleCallback(function () { window.rudderSnippetLoader(); })
            : window.rudderSnippetLoader();
        },
        8000 || 1000
      );
    
      rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}
  ;
That’s how it outputs on the page
g
Ok. So you're using the script tag, not the npm module. And that should work. If you define script as defer, it should execute only after the DOM is loaded. On first look, I see two things •
defer=""
I'm not familiar with this type of declaration of defer. I have seen
<script defer src="....
though • I'm not familiar with RudderStack
loadType
config. I didn't find it in the docs here
Which docs are you looking at where you found
loadType
config?
s
loadType is what sets defer or async. I think defer=“” is a typo I cut and paste from the console. In the console it says; <script defer src=“https://cdn.rudderlabs.com/v1/rudder-analytics.min.js”></script>
When I change loadType to async the script changes to “script async src=” so that’s all that setting does.
g
Got it. So this config is working.
s
Yes it seems too. I can see in the output 8000 | 1000 but am not sure why 1000 would be there?
I set the delayLoadTime to 8000 so the 8000 I understand.
But why is the 1000 there?
g
I think that's OK. If 8000 was not defined, it would have picked the default 1000
s
I know 8000 is a long time, but I tried it to see if it made a difference. I’d probably be Ok with 3500 just to get to LCP first.
g
The code looks right to me.
Ideally I’d like to load it at the end of the page load not the beginning
This must be happening with this code
Why do you say it is happening otherwise. Did you check the network tab?
s
But it doesn’t it’s still loading 9th in the waterfall and scoring poorly on page speed (google core vitals). It also shows 1 second to load. take a look at the dev site here;
our dev site URL is
To me this seems to wait 1 second then start loading. Not 8 seconds as it should. (and therefore everything else would load first).
Hence my question about 8000 || 1000 in the code.
g
I see defer and delayLoadTime are two conflicting things. When using
defer
, it is the execution of the script that happens after load. But the script is downloaded during html parsing. I don't have idea about how
delayLoadTime
is supposed to behave when used in combination with defer.
s
ok. I’ll try that.
g
Although I see that
delayLoadTime
is not explained properly, I assume it is useful in cases when you want to manually load the script. But here you don't want to go about manually loading the script, rather your goal is to optimise the page performance (correct me if I'm wrong). So in that case, I'd simply avoid changing
delayLoadTime
and just use
loadType
defer as you have. And I think that would be all for the page optimisation you need because in case of
defer
browser decides the best possible time for that script to load based on the computing resources available and based on other scripts you have on your page.
s
Ok, I just tested and it did the same thing. But I do see in the code (view source) then following;
<script defer=“” src=“https://cdn.rudderlabs.com/v1/rudder-analytics.min.js”></script>
defer=“”
so could that be an error with the plugin?
g
I see this on the page. It's fine.
s
I had loatype: ‘defer’ as suggested in the comments. Should it be loadtype = defer without the apostrophes
g
no
it should be string
s
g
1. I think, you don't have any performance issue with the code you have. You can also check google's PageSpeed analytics, it does not report any such issue. 2. But I do have some other concerns with the code that I see on your page such as the script tag just above
<script defer src="..rudder-analytics.min.js"
. You are using the script before even it is loaded or maybe I'm missing something. Anyway, for now, you're fine. If you don't see any event in your RS dashboard, likely it is the #2 point I'm mentioning
s
Google’s page speed analytics scores us at 63 and calls out rudderstack as a blocking script.
I haven’t physically inserted the script anywhere. All I have done is follow Rudderstacks best practice according to the gatsby plugin setup. So I’m at a loss to know why its taking a second off loading. On mobile that is a big deal for us.
g
Let me take another look into this
s
Yes regarding point 2 I agree. As I said all I've done is followed the Rudderstack docs. The only settings I've changed are in the Gatsby-config.js. I haven't coded the header myself.
Just a comment on this, I understand that the desktop version is well optimised already and can understand your confusion if I wasn’t clear earlier. 98/100 page speed for the desktop is just fine. Its only the mobile I’m optimising now where we score 67 on google. The rudderlabs script loads first. We start rendering at 1.2 seconds on a 4G connection and rudderlabs starts loading at 1.6seconds. Its then downloading for nearly 0.4 of a second stopping everything else while it does so. What I need is a way to either load it last (from the footer) using the SDK/Gatsby config or a way to delay it. It seems using the gatsby config loads it first from the header of the page no matter what we do. So what would be the advice for me to load in the script from our footer? if I just reference the script link with defer added and comment out the gatsby config will it still work?
g
if I just reference the script link with defer added and comment out the gatsby config will it still work?
Yes. Just comment out gatsby config and then add the reference of rudder script wherever you find it fit.
s
So I ran into issues with that too. I don’t have time to continue with this now, but if the SDK devs come back with something about the plugin that will help (especially around the defer issue) then please let me know.
s
cc @high-zoo-17436
👍 1
h
@salmon-plastic-31303 the Gatsby output plugin code loads the SDK on two triggers (whichever happens first): • First page scroll action • After
delayLoadTime
seconds Can you check that please? If possible, can you integrate the Gatsby plugin back so we can investigate further?
s
Hi @helpful-daybreak-79835. When I use delayLoad (set to true) and delayLoadTime of 8000 (8 seconds just as a test) the script still loads in 1.2 seconds and holds up all other scripts for 0.4 second.
The first page scroll shouldn’t happen as these are programmatic tests carried out by Google and webpagetest.org.
I didn’t attempt to load the script in the footer in the end so I am still using the plugin.
h
Along with
delayLoad
,
delayLoadTime
can you set
loadType: 'defer'
and let us know the result.
s
if you can’t see my result add https://www.dev.toristy.com to the test
You’ll see rudderstack appears 9th in the waterfall at about 1.2 seconds. My setting is delayLoad: True delayLoadTime: 4000 manualLoad: false loadType: ‘defer’
h
Yes I can see the result.
s
I did manage to move google scripts using gatsby’s ScriptStrategy called offMainThread
That did what I was looking for. But the gatsby plugin for rudderstack only seems to inject the code with the settings in the header but it doesn’t actually do anything. defer also looks like some kind of typo
h
The usual flow of the SDK is: 1. Download the SDK i.e. rudderanalytics.min.js from the CDN. 2. Load a script to call the load API with writekey, dataplaneUrl and options. 3. Then it executes the events like page(). With
delayLoad
and
delayLoadTime
this script loading is delayed. So if you expanded the waterfall view you will see that is happening after the given time.
s
Yes but there is no controlling it. The script loads from the CDN with a blockage of 400 ms in the middle of my FCP metric. Ideally it would load immediately after at around position 19. is there an option to load the script from the footer rather than the header?
IE your script is 117KB which even coming from the CDN takes quite a while to load.
All of my other scripts together don’t come to that much.
h
Use the latest SDK, by adding
useNewSDK: true
in the plugin options.
Size of the latest SDK is 40 kb.
s
ok, I don’t see that option in gatsby. Should I just add it after loadType?
h
Yes
s
in loadOptions?
h
@salmon-plastic-31303, there is no functionality in Gatsby to load tags directly in the footer.
You can configure
useNewSDK
next to
loadType
s
so like so…
loadType: ‘async’, useNewSDK: true,
h
Yes
There is
setPostBodyComponents
support in
onRenderBody
API but not sure, if that'll serve your purpose. Anyway, we'll check it out.
s
usenewSDK made a noticable difference.
40K versus 117K knocked about 150-200 ms of load time. Strangely defer loads the script earlier than async.
I also notice that in the code both async and defer seem to be looking for a string
<script async=“”
I would’ve thought it should just be <script async src
h
Strangely defer loads the script earlier than async.
Can you try this set up on a simpler site version to investigate further?
The plugin adds
<script async >
for the rendering. Maybe the browser is interpreting it as an empty string. Which browser are you checking this on?
s
Chrome
the plugin appears to be adding script async=“” or script defer=“”
is that expected?
s
ok. well this is the output in the browser
Same happens with defer
h
async
is equivalent to
async=true
. Same with defer. It defaults to
true
.
s
I know but all I am saying is that async=“” may not be equivalent to async=true in the browser.
Or is it expected behaviour?
h
I'm not sure why the browser is rendering that way. Anyway, we'll fix this to avoid any confusion.
I just tested this myself and confirmed with my team as well, having the
async
keyword is enough to change the script load type i.e,
async
,
async=true
,
async=""
, etc. are all equivalent in behavior.
It'd be easy to debug if you could try to replicate this setup but on a lighter/simpler site version.
s
It’s really this one I need to work on. I have more complicated cases coming. This is one of the easiest. Is there a way to cache the script?
h
The browser should cache it for about 1 hour
s
Yes, by default. Google is saying could we cache it for a year? Would that mean the script wouldn’t work?
h
Our CDN sends the cache age header in the response which is set to 1 hour.
s
Does defer or async work if I have set the loadTime?
I no longer see it in the script output.
h
@salmon-plastic-31303, sorry for the late response. Yes, defer and async load types would work.
h
Hi @salmon-plastic-31303, We release a new version(2.0.0) of the plugin where we have modified the logic around delayLoad. Do try it out and let us know if everything is working fine for you.
s
Hi Moumita, happy to do so, where are the spec changes?
s
So will this automatically update? IE: set delayLoadtime to 1500 and it’ll modify? I am also using “useNewSDK: true,” as this made a big difference. Should I remove?
h
Now the default SDK is v1.1, “useNewSDK: true,” will be ignored. Better to remove it.
Yes set delayLoad: true and delayLoadTime: 4000 and you will see the SDK will be loaded after 4 sec
s
Ok trying it now.
h
And first update the plugin to latest version i.e. 2.0.0
s
ok I tried “yarn upgrade gatsby-plugin-rudderstack” but the version is still 1.1.2 in package.json
Am I using the wrong command here?
nevermind, I added the latest flag and it worked.
I’ll now do the test
Yes it works as you described. Very big difference. Not to my page speed but to when your scripts load, which is much more expected behaviour.
🙌 1
Yes. So when I remove the load type as “async” and just set to default and my pagespeed is up 20 points. So this is working exactly as it says on the tin. Very good support thanks.
That’s what I was aiming for. Above 90 on mobile with tracking (or any other scripts) loaded afterwards.
h
Great
h
@salmon-plastic-31303, that's great news! In fact, we just published v2.0.0 which even delays the SDK script tag addition using the same flag.
h
If you are using yarn then you can use the command:
yarn add gatsby-plugin-rudderstack@2.0.0
Oh you used the
latest
flag that is also fine
@helpful-daybreak-79835, He is using 2.0.0
👍 1
s
Yeah I updated it already. But seriously guys thanks for listening. I thought I was going mad for a while there. It seemed a logical thing to do, set it to load after my site and everything else will load after that. Like how defer should work. But this delayLoad method now seems to override defer or async (loadType string). So I would advise leaving that as default > that was when I saw a huge bump in speed.
🙌 2
h
@salmon-plastic-31303, the
loadType
is still respected now. It's just that the SDK script tag gets added to the page after the wait time specified in the
delayLoadTime
with appropriate load type set.
g
That's amazing. Thank you @salmon-plastic-31303 for bringing to the notice and @high-zoo-17436 @helpful-daybreak-79835 for your hard work 🚀
s
@helpful-daybreak-79835 understood, but when I tested it with a 4 second delay and async I got the delay but not the speed benefit. When I switched to defer it was slower. When I put it to default (neither specific setting I guess) it worked above 90 on Google lighthouse (mobile) which was my consistent testing platform, some 20 points higher than with the async or defer setting. I'm not sure based on what you said why that would be the case, but am happy it worked.
👍 1