动态插入script标签并执行回调

在看到 polyfill.io后里面有个动态插入polyfill的关键点,感觉挺巧妙的,以后遇到这种类似需求也可以照着去实现

// Create a list of the features this browser needs.
// Beware of overly simplistic detects!
var features = [];
('Promise' in window) || features.push('Promise');
('IntersectionObserver' in window) || features.push('IntersectionObserver');
('after' in Element.prototype) || features.push('Element.prototype.after');

// If any features need to be polyfilled, construct
// a script tag to load the polyfills and append it
// to the document
if (features.length) {
  var s = document.createElement('script');

  // Include a `ua` argument set to a supported browser to skip UA identification
  // (improves response time) and avoid being treated as unknown UA (which would
  // otherwise result in no polyfills, even with `always`, if UA is unknown)
  s.src = 'https://polyfill.io/v2/polyfill.min.js?features='+features.join(',')+'&flags=gated,always&ua=chrome/50&callback=main';
  s.async = true;
  document.head.appendChild(s);
} else {

    // If no polyfills are required, invoke the app
    // without delay
    main();
}

function main() {
    console.log('Now to do the cool stuff...');
}

实现原理其实很简单,只需要在加载的脚本最后面添加执行函数就可以,
例如上面的脚本加载结束之后的例子:

/* Polyfill service v3.25.1
 * For detailed credits and licence information see https://github.com/financial-times/polyfill-service.
 * 
 * UA detected: chrome/63.0.0
 * Features requested: IntersectionObserver,Promise,after
 *  */

(function(undefined) {

/* No polyfills found for current settings */

})
.call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});

typeof main==='function' && main();

重点在最后一句typeof main==='function' && main();

举一反三:

此种方法也可以加载服务器上的静态资源数据,
将服务器上的数据使用*.js,然后里面就放一个执行函数,当然此时也可以携带参数数据,当用script标签动态加载后,这个执行函数就会执行.实现了动态加载数据.

// 首先定义执行函数, 当数据加载完之后就会执行此函数
 window.eqfeed_callback = function(results) {
        for (var i = 0; i < results.length; i++) { 
            console.log(i)
   }
}
var script = document.createElement('script');
script.src = 'https://localhost/data/data.js';
document.getElementsByTagName('head')[0].appendChild(script);

data.js数据为:

eqfeed_callback([
1,2,3,4,5,6,7,8
]);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,337评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,241评论 4 61
  • 书中所提的“大脑活用学习法”,就是通过了解大脑的特性以及寻找适合大脑的学习方法,使自己形成一种享受学习的“学习习惯...
    何舒卉阅读 1,450评论 0 12
  • 我的心理世界大概是扭曲的,陷进去的时候自己都没有发现,没有挣扎一下 我的性格大概是狭隘的,小格局的,有井底之蛙的姿...
    简生风发阅读 194评论 0 0
  • 3.冯神神啊 近几年,一个人或和朋友去过不少的地方,很少在同家人一起出行。我一直坚持,去一个陌生的城市,不是冲着它...
    冯神神啊阅读 286评论 4 3