开发者

Embedding inline JS script instead of making an AJAX request. Why?

开发者 https://www.devze.com 2023-01-08 21:09 出处:网络
I noticed that some websites (for example: apple.com or disqus.com) don\'t send AJAX request to load, for example, live search results. Instead they attach new JS script, that holds all results in a v

I noticed that some websites (for example: apple.com or disqus.com) don't send AJAX request to load, for example, live search results. Instead they attach new JS script, that holds all results in a variable.

To be more specific. If you go to apple.com and type "test" 开发者_C百科into the searcher. It won't send an AJAX request to get the results, instead it will add < script src="some.addres.apple.com/result.js?q=test" > to the HTML and execute new piece of JS script to bring in the search results. improvement Are they doing this only because you can't send AJAX request to a different domain, or is there any speed improvement possible?


There is a lot of discussion online of the "hackishness" of JSONP:

  • http://insideria.com/2009/03/what-in-the-heck-is-jsonp-and.html
  • http://www.west-wind.com/Weblog/posts/107136.aspx

I have found it to be extremely useful in getting around cross-domain security limitations but I have not seen nor have I heard of any speed improvements.

I highly recommend learning more about JSONP (especially when it is useful/necessary).


This approach called jsonp. Instead of calling ajax request script appends new script tag that contains data wrapped into callback function (like onComplete callbacks for ajax calls). It helpful in cases when you need request to another domain. Otherwise (in my opinion) ajax calls preferable, e.g. it has has proper error, success and timeout callbacks.

more about Jsonp


One of the main advantages of the JSONP technique is that since now your search functionality is being served from a different server and you have gone ahead and taken the pain to develop a JSONP response mechanism, You can go ahead and embed that search wherever you want.

So in your particular example, Apple can use the same search (if it encapsulates their other ecosystems as well) to serve results maybe for example on another sister website.

In terms of performance, As pointed out by @fantactuka, AJAX calls are preferrable according to me also as script injection is costly and provides less ways to handle when stuff goes wrong.


I believe that this a means of working around the limitation imposed by the browser that requests must be directed to the same server from which the page was loaded.

0

精彩评论

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