0

I have a javascript script that I want to load synchronously, but the URL of the script is determined by the value of a cookie. For example:

<script src="/js/[user-id-from-cookie].js"> 

This script has to load in the <head> of my HTML document and must be run synchronously (it has to block the main thread while it is downloaded and executed).

How can I use javascript to:

  1. Read the value of a cookie
  2. Download and execute the script synchronously

I need to do this in pure javascript, no frameworks like jQuery etc.

Thanks!

4
  • 2
    I think you may try document.write. But why you need it to load synchronously? Commented Jul 3, 2020 at 13:56
  • This is an A/B testing script, and therefore if the script loads synchronously there may be perceptible "flicker" for end users if rendering has started before the script can run. Thanks! Commented Jul 3, 2020 at 13:58
  • I think you mean asynchronously in you comment. because your question and comment doesn't match otherwise. But then I'm not sure why a script would cause flicker? Commented Jul 3, 2020 at 14:16
  • Oh yes, I meant synchronously. Basically I want the script to run before anything is rendered. If a button gets rendered to the screen with a blue background, and I want to test it with a red background if the script loads asynchronously then the user may see a blue button initially and it will suddenly "flick" to red once the JS code runs. Your answer has worked, so if you want to post it as an answer I'll be happy to accept it! Thanks!! Commented Jul 3, 2020 at 14:33

1 Answer 1

1

You can use document.write to load scripts synchronously.


But use it this way may cause some lag, I'd like to offer some alternatives.

  • parse the cookie and return different script per user by server. (recommended, but need to have server support)
  • load all the script, but rewrite them so only one would execute based on condition. (not good for large amount of variant, of course)
  • hide the body and only show after whatever preprocess have done. (not actually how to load script, but then you can load it asynchronously)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the other tips! I'll explore server side next, but this is react, so the HTML isn't generated dynamically.
glad to help :) I'm not using react, so can give no advice for it :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.