Thomas Clayson
Thomas Clayson

Reputation: 29935

Load a script synchronously before render (programatically in <head>)

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!

Upvotes: 0

Views: 215

Answers (1)

apple apple
apple apple

Reputation: 10604

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)

Upvotes: 1

Related Questions