load jQuery from external source if not loaded

后端 未结 5 1515
臣服心动
臣服心动 2020-12-05 12:12

load jQuery from source

What I like to do is to drop my local jquery.js and have it hosted somewhere else. But what if Google is down? So let\'s cod

5条回答
  •  死守一世寂寞
    2020-12-05 13:13

    The problem

    If you use Firebug and see where jQuery gets loaded you can see taht Google successfully loaded it. Why it doesn't seem to work? Because requests are asynchronous and while your script runs synchronously it executes all steps before the first script gets loaded.

    So:

    1. jQuery not present.
    2. Add SCRIPT element to load from Google (browser sends a request and continues execution of the script)
    3. jQuery not present add another source
    4. ...

    etc etc.

    Solution

    What you should do is attach to onLoad event of your script loading elements and check for jQuery after they've loaded.

    Script executes lightning fast compared to sending a request out to some server on the internet and getting results back for processing.

    Additional notes

    As I've read you're going to have problems detecting 404s using this technique. Suggested way would be to use Ajax (XHR) and then attach script element and add received content to it. This would be the most reliable way of doing it for all browsers.

提交回复
热议问题