[英]How to load all scripts, stylesheets, and markup from one js file?
以下一小段代码一经部署(在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
文件中包含样式表,如下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();
});
};
如果您希望以类似于$.getScript
的简单方式异步加载CSS,请查看loadCSS ,这是一个独立的库,用于加载CSS,而无需依赖jQuery。
如果您的CSS也位于该js文件中,则只需将CSS代码添加到文档样式标签中即可。 在某些情况下,例如不允许使用不同的css文件的情况下,它可能很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.