以下一小段代码一旦部署就无法更改(它在 RIA 中)因此所有内容都必须通过 bootstrapper.js 文件加载:
<div id="someDivID"></div>
<script type="text/javascript" src="bootstrapper.js"></script>
加载所有 js、css 和标记的最佳方式是什么?是否有比以下方法更好(更干净、更快、更清晰)的方法?:
function createDivs() {
var jsDiv = document.createElement('div');
jsDiv.id = 'allJavascriptHere';
var contentDiv = document.createElement('div');
contentDiv.id = 'allContentHere';
document.getElementById("someDivID").appendChild(jsDiv);
document.getElementById("someDivID").appendChild(contentDiv);
function importScript(url){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.getElementById("jsDiv").appendChild(script);
}
importScript("http://example.com/jquery-1.4.2.min.js");
importScript("http://example.com/anotherScript.js");
}
window.onload = function(){
$.get("http://example.com/someHTML.html", function(data) {
$('#contentDiv').html(data);
setTimeout("javaScript.init()", 200);
});
}
someHTML.html
文件中的样式表如下:
<style type="text/css">
@import url("example.com/styleSheet.css");
</style>
(注意:我不知道为什么我需要 setTimeout
但出于某种原因我需要。也许你的答案不需要它。)
最佳答案
您可以使用 jQuery 的 $.getScript()
导入脚本。
我最近写了一个导入 CSS 的函数。
var getCss = function(file, callback) {
if (typeof callback !== 'function') {
throw 'Not a valid callback';
};
$.get(file, function(css) {
var top = $('head > link[rel=stylesheet]').length ? $('head > link[rel=stylesheet]:last') : $('head > *:last');
top.after('<link rel="stylesheet" type="text/css" href="' + file + '">');
callback();
});
};
关于javascript - 如何从一个 js 文件加载所有脚本、样式表和标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3994184/