简体   繁体   English

如何从一个js文件加载所有脚本,样式表和标记?

[英]How to load all scripts, stylesheets, and markup from one js file?

The following small snippet of code cannot be changed once deployed (it's in an RIA) so everything must be loaded via a bootstrapper.js file: 以下一小段代码一经部署(在RIA中)就无法更改,因此所有内容都必须通过bootstrapper.js文件加载:

<div id="someDivID"></div>
<script type="text/javascript" src="bootstrapper.js"></script>

What's the best way to load up all the js, css, and markup? 加载所有js,css和标记的最佳方法是什么? Is there a better (cleaner, faster, crisper) way than the following?: 有没有比以下更好(更清洁,更快,更清晰)的方法?:

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);
   });
 }

with stylesheets in the someHTML.html file as so: someHTML.html文件中包含样式表,如下someHTML.html

<style type="text/css">
   @import url("example.com/styleSheet.css");
</style>

(note: I don't know why I need the setTimeout but for some reason I do. Maybe your answer won't require it.) (注意:我不知道为什么需要setTimeout但是出于某些原因,我确实需要。也许您的答案将不需要它。)

You can use jQuery's $.getScript() to import scripts. 您可以使用jQuery的$.getScript()导入脚本。

I recently wrote a function to import CSS. 我最近写了一个导入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。

If your css is also in that js file, you can simply add css code to the documents style tag. 如果您的CSS也位于该js文件中,则只需将CSS代码添加到文档样式标签中即可。 It can be useful in some situations, where using different css file is not allowed etc. 在某些情况下,例如不允许使用不同的css文件的情况下,它可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM