Jos*_*ada 2 html javascript jquery
我知道我的主题非常棘手,但我不知道如何在这个主题上更加精通它.所以这里是怎么回事.我有一个按钮
<a href="#" onClick="loadtheFile()">Load IT!</a>
Run Code Online (Sandbox Code Playgroud)
在脚本标签上:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
alert("done! the file has been loaded");
}
Run Code Online (Sandbox Code Playgroud)
脚本很好,加载时会自动有一个模态框.但问题是,我的警报似乎首先发射的是脚本
那我怎么知道我是否已经完成加载脚本?
更新第一次尝试回答:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
$(document).ready(function() {
alert("done! the file has been loaded")};
}
Run Code Online (Sandbox Code Playgroud)
同样的问题
alert确实在加载脚本之前运行.将script标记附加到页面的所有内容都是将标记附加script到页面.然后浏览器必须下载脚本,一旦收到,就运行它.那是在你的loadTheFile功能退出之后.
因此,您需要在实际加载并运行脚本时获得回调.这比以前更加标准,但仍然存在一些跨浏览器的麻烦.幸运的是,jQuery已经为你解决了这个问题(因为你已经使用了jQuery):
function loadTheFile() {
$.getScript('http://www.thisismyexternalloadingjsfile"')
.then(function() {
alert("done! the file has been loaded");
});
}
Run Code Online (Sandbox Code Playgroud)
你的评论:
但我的脚本文件有data-*属性
假设你在谈论标签data-*上的属性,那么你将不得不做更多的工作,但它仍然相当直接:script
function loadTheFile() {
var load = $.Deferred();
var script = document.createElement('script');
script.src = 'http://www.thisismyexternalloadingjsfile"';
// No need for `type`, JavaScript is the default
script.setAttribute("data-foo", "bar");
script.onreadystatechange = function() {
if (script.readyState === "loaded") {
load.resolve();
}
};
script.onload = function() {
load.resolve();
};
load.then(function() {
alert("done! the file has been loaded");
});
document.body.appendChild(script); ;// Or wherever you want to put it
}
Run Code Online (Sandbox Code Playgroud)
该onreadystatechange位是处理旧版本的IE.