JS对外部文件的加载:
- 使用
- 使用XMLHttpRequest对象异步加载JS文件
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}loadScript("path/to/external/script.js", function() {
console.log("Script loaded");
});IFRAME的加载:
- 通过JS创建IFRAME元素
var iframe = document.createElement('iframe');
iframe.src = 'path/to/external/iframe.html';- 修改IFRAME的src属性
var iframe = document.getElementById('myIframe');
iframe.src = 'path/to/external/iframe.html';当加载完成后,指定指向方法的实现:
- 使用传统的回调方式:
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}loadScript("path/to/external/script.js", function() {
console.log("Script loaded");
});- 使用Promise方式:
function loadScript(url) {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = resolve;
script.onerror = reject;
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
});
}loadScript("path/to/external/script.js")
.then(function() {
console.log("Script loaded");
})
.catch(function() {
console.log("Error loading script");
});示例说明:
- 加载外部JS文件并指定回调方法的示例:
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}loadScript("https://code.jquery.com/jquery-latest.min.js", function() {
console.log("jQuery loaded");
});- 加载IFRAME并指定回调方法的示例:
var iframe = document.createElement('iframe');
iframe.src = 'https://www.baidu.com';
iframe.onload = function() {
console.log("IFRAME loaded");
};
document.body.appendChild(iframe);本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JS对外部文件的加载及对IFRMAME的加载的实现,当加载完成后,指定指向方法(方法回调) - Python技术站