Dynamic Loading: Pass back url to script or pass back script itself?
I've been wondering if there is a right way to do this: When I'm dynamically loading a开发者_StackOverflow中文版 script using AJAX, I have the option of passing back a url to the script on the server and then running a: <script src = response.url ></script>
or just passing back the script itself.
I went with the approach of passing back the contents script itself because I figured I only make one roundtrip instead of two. Also because I want to pass back some css or other assets as well. I noticed however that facebook passes back urls to CDN resources, so I'm wondering if my approach has some consequences that I'm overlooking.
Thanks! Matt
When you're facebook, you're looking at some rather unique traffic patterns. Sending back 20KB of script vs sending 30 characters from dynamic servers can translate into a lot more load on those servers. Additionally, they might not be able to serve large-ish content all that fast.
In contrast, the CDN servers are glorified static proxies, designed for speed and for scale. So from facebook's point of view, the additional round-trip makes sense, as it can still improve the overall page speed, and it certainly improves their server traffic patterns.
Now back to you. This approach won't make sense if you're going to load the script from the same servers as the rest of your site. If you do have access to a CDN as well, then you have to do the math using various assumptions about your users (latency, location), facts about your site (size of scripts, timing of script loads), and compare the effect of having your main servers serve those scripts, versus the extra round-trip and your CDN servers handing out those scripts.
One additional thought about roundtrips: If I was facebook, I'd probably be handing out those CDN URLs early on, before the page actually needs to load the scripts. Ideally, I'd piggyback on another request to sneak that little bit of extra data in. That'd make the extra round-trip issue mostly moot.
Hm, well I'm fairly sure there are some cross-domain security issues with AJAX, meaning if you were trying to dynamically load a script's content from an external CDN, you'd need to work around such an issue..
精彩评论