动态插入script标签并执行回调
2017-07-10 本文已影响284人
wwmin_
在看到 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
]);