通常,您将所有框架(脚本和css(放在HTML源代码的head元素中,并且在渲染页面时将加载它们。例如,我想加载jQuery和boostrap,它看起来像这样:
<html>
<head>
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<link href="jquery.min.css">
<link href="bootstrap.min.css">
</head>
</html>
但是想象一下这样的情况:你从一开始就只加载了jQuery,你想执行一个操作,比如点击一个按钮,并且需要一些框架功能,比如引导程序提供的东西,它们需要在点击后立即加载。
在我的理解中,这并不像听起来那么容易,因为在端已经渲染后需要加载的框架需要执行 OnReady 调用。有没有简单的方法可以实现这一目标?
亲切问候马吕斯
"想象一下,你从一开始就只加载了jQuery,你想执行一个操作,比如点击一个按钮,并且需要一些框架功能,比如引导程序提供的东西,它们需要在点击后立即加载。
您所描述的是依赖项的延迟加载。
RequireJS在这方面做得很好。
如果您正在考虑这样做以加快用户的页面加载性能,您可以简单地使用标签的 async 属性,如下所示:
<script src="jquery.min.js" async></script>
阅读有关异步加载的更多信息 https://css-tricks.com/thinking-async/
如果您有其他原因在某个事件后加载 js,请使用以下方法:
function loadJavaScript(url)
{
var s = document.createElement('script');
s.setAttribute('src', url);
s.setAttribute('async',true);
document.head.appendChild(s);
}
您可以将脚本的地址作为loadJavaScript('https://ajax.googleapis.com/ajax/libs/dojo/1.12.2/dojo/dojo.js')
更新
在脚本加载时使用 onload 处理程序调用函数:
$(document).ready(function() {
$('#test').click(function() {
console.log("oO");
loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
loadJavaScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.js',function(){
$('.selectpicker').selectpicker('refresh');
});
});
});
function loadCss(url,fn) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
function loadJavaScript(url)
{
var s = document.createElement('script');
s.setAttribute('src', url);
s.setAttribute('async',false);
if(typeof(fn) == "function")
{
fn();
}
document.head.appendChild(s);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test" type="button" class="btn btn-primary">Basic</button>
<select class="selectpicker">
<option>1</option>
</select>