I'm currently building a little SPA framework of my own. I'm just curious, how does some things work in a background.
Let's say, I want to dynamically import a script from the server.
The method that I'm currently using is including a script tag to the head, with "async" attribute set to true. Something like this.
for (let requiredScript of requiredScripts){
var $head = document.getElementsByTagName('head')[0];
var $script = document.createElement('script');
$script.src = requiredScript;
$script.async = true;
$script.onload = function(){
callback();
}
$head.appendChild($script);
}
How does this work exactly in browsers? I read that browsers spawn a new thread for every script in the head tag, and when they load, they exacute them. (I could also use defer attribute, but it doesnt matter there).
This (if it works as I expect it to work), is great. Syntax is ugly, but it works. With a little disadvantage: I can't explicitly set the header for those requests. For example, I want to add a JWT token to every request for restricted resource, which I can't, and I have to use ajax call. But this is not a part of this question.
So, second way to load my resources (there's a third way, ES6 import, but I'm not gonna use this for now) is to load my resources via an AJAX call. But from the nature of XMLHttp request, I get only a string, or maybe JSON, but not a script, so I have to call eval(), which is both slow and insecure.
But let's get to the question. What exactly is a resource call in a script tag? How does it differ from xmlhttp request (or an ajax call)? What exactly does browser do, when parsing html file and evaluating the line with script tag? Can I import a javascript file as a binary file, and make browser just execute it? (faster and safer option that eval()). I want to have full control and understanding behind what I'm doing, but I feel very confused and can't find the right answers on this topic.
Every explanation (or even a helpful link) would be much appretiated.
eval()it, though there are some slight differences in some obscure details about howeval()works.<script>tag processing.