There is a cool feature on modern browsers that When the browser is blocked on a script, a second lightweight parser scans the rest of the markup looking for other resources e.g. stylesheets, scripts, images etc., that also need to be retrieved. How can I have a script block that simply blocks the lookahead/preloading of resources until this script block has finished executing.
I suggest a
<script sync> attribute that should do just this…
See Stack Overflow related question
Scripts are already sync by default, and making them more sync would require a significant use-case to justify, because it’s user-hostile. (That’s why we have the
defer attributes, to make them less sync, and are trying to find more ways we can reduce their impact on the page.)
In this case, your actual problem is simple to solve - set the cookie with a response header, not a script in the page. That way all the resources on the page will have the correct cookie set automatically. This is pretty simple to do in any web programming framework.
I’ll give you an example why we need to set it on the page via js, we have lots of bots who crawl our pages and we want to make sure that the resources that are requested are only for users with JS.
So the (maybe only) way to do it is to set a cookie and then all resources (images, stylesheets, scripts) will be called with that cookie.
Any other ideas?
Still if you don’t want to set the cookie with response header as suggested before, You can make your script not pre loadable by adding them dynamically to the page like
document.cookie = 'b=p; path=/';
var a = document.createElement('script'); a.src = 'your script here';
And what about images?
<img src="/path/to/image/"> ?
and the stylesheets files?