I have a javascript tag embedded in the <head> of a webpage. In this script (served via Amazon Cloudfront) it does some processing and then if certain checks are set, appends another script to the document head. Here is an example of that embed:
var js = document.createElement('script');
js.src = 'http://cdn.mysite.com/script.js?cache_bust='+Math.random();
document.getElementsByTagName('head')[0].appendChild(js);
This works properly, however it’s non-blocking meaning the webpage continues to load while that script is being appended to the head.
Is there any way to embed a script in a blocking manner so the webpage “hangs” while the new script is setup?
I was thinking about maybe moving the first script to just below the <body> tag and then using document.write() the second script but I’d prefer to keep it in the <head>.
Any ideas? Thanks!
You’re right,
document.writeshould work. As Dr.Molle mentioned in the comment, you can use inside the<head>too (the<head>is part of the document too!).So:
The
'</scr' + 'ipt>'part is a precaution, browsers usually think the outer script block is being closed when they find</script>, even if inside a string.