开发者

Do Browsers cause Interrupts to their JS when receiving a response?

Assume, for whatever reason, that we have three inline scripts on a page. Each of these scripts are functionally the same, and all three will create a script tag, with the source set to a server-side script (each with slightly different parameters) which returns JS to execute. Assume this JS contains a global variable containing important parameters for the function it calls at the end.

var g_important = {"arbitrary1":"someval1", "arbitrary2":"someval2"};
doSomething();

The script in question resides on a CDN with a load balancer. Assume that each request from our original JS could actually be sent to a different serv开发者_Go百科er. The response time from the server is now variable, meaning we might get our response to the second request first. That's not a problem because we send a reference value back with the code, ensuring that we're at least working with the specified object.

My question is: what happens when we get two responses at roughly the same time? This is a very unlikely case, but if the first response is in the process of executing doSomething() when the second response comes in, what does the browser do? Does it parse the value for the variable and push the second doSomething call onto the stack?

Assuming this is the case, doSomething could be working with the wrong set of values in theory. I can't recreate this case, as the timing would have to be absolutely perfect, but I need to know if it's a problem.


Javascript operates "one line at a time". Scripts will always be stacked if another script is running.

And technically, 2 scripts cannot be loaded at the same time, so 1 will be executed before the other.


It depends on how you inject the script. Techniques vary in success of ensuring the order of execution. The common and simple document.createElement + head.appendChild way will not ensure order in IE for example.

more info at Load script without blocking


So you're worried that the g_important object could change during the execution of doSomething()? I don't think this is possible, but if you're worried about it, why not register doSomething() as a callback on the completion of each AJAX request. Then each call to the function gets passed the data for its request and never the others.

Maybe I don't fully understand the situation, but this kind of thing would seem to be easily avoidable, if its even possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜