1

我一直有这个疑问,我想在从该 URL 加载脚本之前测试一个 URL 是否存在,但是我尝试这样做的方式失败了,因为我正在使用 XMLHTTPRequests 并且很多人都知道,当你使用此方法从服务器获取文件,它与执行 GET 的脚本不同,您将返回is not allowed by Access-Control-Allow-Origin.

那么,为什么Modernizr.load()方法理论上可以加载脚本,而我什至看不到那里是否真的有东西呢?

4

1 回答 1

2

Because Modernizr.load(), like @dm03514 mentions, loads the script not through XMLHttpRequest, but by inserting a <script tag which doesn't have the cross-domain restriction. It then tries to check if the script loaded correctly, but that's not an easy task and it may not be possible in all browsers. For more detail you can see this recopilation of the support of different browsers for the various options available for checking success of loading scripts/css: http://pieisgood.org/test/script-link-events/

As for why XMLHttpRequest fails, you can read more about cross-domain restrictions at MDN: https://developer.mozilla.org/en-US/docs/HTTP_access_control

Some motivations for using script loaders are:

  1. Loading scripts based on conditions like what yepnope and YUI do
  2. Load scripts asynchronously for performance reasons ( tags block the rendering of the page).
  3. Dependency injection (load resources that other scripts need, this is what requirejs does)
  4. Load scripts when certain events happen (load hew functionality when a user clicks on a tab)

Also when you use script loaders, you usually load everything from them, including your application code, so that your application code has access to all dependencies. The require.js model (google AMD modules) is a great way of organizing your app. It allows you to write small modules that do specific tasks and reuse them, instead of one big file that does everything.

于 2012-10-21T20:30:45.807 回答