[英]Embedding inline JS script instead of making an AJAX request. Why?
I noticed that some websites (for example: apple.com or disqus.com) don't send AJAX request to load, for example, live search results. 我注意到一些网站(例如:apple.com或disqus.com)不发送加载的AJAX请求,例如,实时搜索结果。 Instead they attach new JS script, that holds all results in a variable.
相反,他们附加新的JS脚本,将所有结果保存在变量中。
To be more specific. 更具体。 If you go to apple.com and type "test" into the searcher.
如果你去apple.com并在搜索器中输入“test”。 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.
它不会发送AJAX请求来获取结果,而是将<script src =“some.addres.apple.com/result.js?q=test”>添加到HTML并执行新的JS脚本引入搜索结果。 improvement Are they doing this only because you can't send AJAX request to a different domain, or is there any speed improvement possible?
改进他们是否这样做只是因为您无法将AJAX请求发送到其他域,或者是否可以提高速度?
This approach called jsonp. 这种方法称为jsonp。 Instead of calling ajax request script appends new script tag that contains data wrapped into callback function (like onComplete callbacks for ajax calls).
而不是调用ajax请求脚本会附加新的脚本标记,其中包含包含在回调函数中的数据(如ajax调用的onComplete回调)。 It helpful in cases when you need request to another domain.
当您需要其他域请求时,它很有用。 Otherwise (in my opinion) ajax calls preferable, eg it has has proper
error
, success
and timeout callbacks. 否则(在我看来)ajax调用更可取,例如它有正确的
error
, success
和超时回调。
There is a lot of discussion online of the "hackishness" of JSONP: 网上有很多关于JSONP“hackishness”的讨论:
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). 我强烈建议您学习更多有关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. JSONP技术的一个主要优点是,从现在开始,您的搜索功能是从不同的服务器提供的,并且您已经开始努力开发JSONP响应机制,您可以继续将搜索嵌入到您想要的任何位置。
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. 因此,在您的特定示例中,Apple可以使用相同的搜索(如果它也包含其他生态系统)来提供结果,例如在另一个姐妹网站上。
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. 在性能方面,正如@fantactuka所指出的,AJAX调用对我来说也是优选的,因为脚本注入代价高昂,并且在出现错误时提供更少的处理方法。
我相信这是一种解决浏览器强加的限制的方法,请求必须指向加载页面的同一台服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.