最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Are you allowed to have an alternate source for a script? - Stack Overflow

programmeradmin0浏览0评论

Is is possible to have an alternate source for a javascript in HTML5? For example, I am using jQuery, and have it locally. But an I allowed to include an alt attribute so that if that doesn't work, Google's jQuery will load?

If it works, the code would look something like this: <script src="enter your text here.js" alt="googlescode"></script>

Is is possible to have an alternate source for a javascript in HTML5? For example, I am using jQuery, and have it locally. But an I allowed to include an alt attribute so that if that doesn't work, Google's jQuery will load?

If it works, the code would look something like this: <script src="enter your text here.js" alt="googlescode"></script>

Share Improve this question asked Sep 7, 2013 at 19:23 tjonstjons 4,7695 gold badges29 silver badges36 bronze badges 2
  • There're many script loaders written in JavaScript. Shall we assume you want a static HTML solution? – Álvaro González Commented Sep 7, 2013 at 19:29
  • Sure, but that is not what my question is about. – tjons Commented Sep 7, 2013 at 19:31
Add a comment  | 

3 Answers 3

Reset to default 8

Yes, you can do it. HTML5 Boilerplate has a good example for jQuery loading.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

But it uses it the other way around. If the script from google couldn't be loaded, it falls back to your local script.

You should load the CDN version as a first try anyway, as it loads quicker than a "local" version.

If it is jQuery, you might want to look at this article.

Snippet:

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script>
<script>
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>

When implementing them I realized all the former answers have the common problem that Chrome will block them with slow connections since document.write is a synchronous function. The issue is discussed in this post.

The solution usually is using a moderns loader, or pre-compiling the js code.

However, if your use-case still requires this approach, you need to use an async call. An illustrative example is the way Google Analytics is loaded.

Basically, the code above translates into:

    <script>window.jQuery || (function(){
        // Create the DOM node
        a=document.createElement('script');
        a.src="http://path-to-the-script.js";
        a.async=1;
        // Find a node, and insert the script before it
        m=document.getElementsByTagName('script')[0];
        m.parentNode.insertBefore(a,m);
    })()</script>
发布评论

评论列表(0)

  1. 暂无评论