Sync attribute for the script element


#1

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


#2

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 async and 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.


#3

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?


#4

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

<script>
        document.cookie = 'b=p; path=/';
</script>
<script> 
    (function(){
          var a = document.createElement('script'); a.src = 'your script here';
          document.body.appendChild(a);
    })()
</script>

#5

And what about images? <img src="/path/to/image/"> ? and the stylesheets files?