      1 /**
      2  * Hilo
      3  * Copyright 2015 alibaba.com
      4  * Licensed under the MIT License
      5  */
      6
      7 /**
      8  * @private
      9  * @class javascript或JSONP加载器。
     10  * @module hilo/loader/ScriptLoader
     11  * @requires hilo/core/Class
     12  */
     13 var ScriptLoader = Class.create({
     14     load: function(data){
     15         var me = this, src = data.src, isJSONP = data.type == 'jsonp';
     16
     17         if(isJSONP){
     18             var callbackName = data.callbackName || 'callback';
     19             var callback = data.callback || 'jsonp' + (++ScriptLoader._count);
     20             var win = window;
     21
     22             if(!win[callback]){
     23                 win[callback] = function(result){
     24                     delete win[callback];
     25                 };
     26             }
     27
     28             src += (src.indexOf('?') == -1 ? '?' : '&') + callbackName + '=' + callback;
     29         }
     30
     31         if(data.noCache) src += (src.indexOf('?') == -1 ? '?' : '&') + 't=' + (+new Date());
     32
     33         var script = document.createElement('script');
     34         script.type = 'text/javascript';
     35         script.async = true;
     36         script.onload = me.onLoad.bind(me);
     37         script.onerror = me.onError.bind(me);
     38         script.src = src;
     39         if(data.id) script.id = data.id;
     40         document.getElementsByTagName('head')[0].appendChild(script);
     41     },
     42
     43     onLoad: function(e){
     44         var script = e.target;
     45         script.onload = script.onerror = null;
     46         return script;
     47     },
     48
     49     onError: function(e){
     50         var script = e.target;
     51         script.onload = script.onerror = null;
     52         return e;
     53     },
     54
     55     Statics: {
     56         _count: 0
     57     }
     58
     59 });