按需加载jquery
一个公共的js使用了jquery
但是有的页面加载了jquery有的又没有加载
这时应该在这个js中做个判断,按需要加载jquery
代码如下
[pcsh lang=”js” tab_size=”4” message=”” hl_lines=”” provider=”manual”]
function withjQuery(callback) {
if(!(window.jQuery)) {
var js = document.createElement('script');
js.setAttribute('src', 'http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js');
js.setAttribute('type', 'text/javascript');
js.onload = js.onreadystatechange = function() {
if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
if(callback && typeof callback === "function") {
callback();
}
js.onload = js.onreadystatechange = null;
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}else{
callback();
}
}
withjQuery(
function(){
$(function(){
// jq中需要绑定的内容
});
}
);
[/pcsh]
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Dev!