代码之家  ›  专栏  ›  技术社区  ›  Kyle Cureau

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

  •  0
  • Kyle Cureau  · 技术社区  · 15 年前

    以下小代码片段在部署后无法更改(它位于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 但不知什么原因。也许你的答案不需要。)

    3 回复  |  直到 15 年前
        1
  •  4
  •   alex    15 年前

    您可以使用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();
    
        });
    
    
    };
    
        2
  •  0
  •   Bick    15 年前

    如果您的css也在js文件中,那么您可以简单地将css代码添加到documents样式标记中。在某些不允许使用不同css文件的情况下,它可能很有用。

        3
  •  0
  •   vhs    11 年前

    $.getScript 退房 loadCSS ,一个独立的库,用于加载CSS而不依赖jQuery。