如何从一个js文件加载所有脚本,样式表和标记? [英] How to load all scripts, stylesheets, and markup from one js file?

查看:81
本文介绍了如何从一个js文件加载所有脚本,样式表和标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下小段代码在部署后(在RIA中)无法更改,因此必须通过bootstrapper.js文件加载所有内容:

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:

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

加载所有js,css和标记的最佳方法是什么?是否有比以下更好的(更干净,更快,更脆弱)的方式:

What's the best way to load up all the js, css, and markup? 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);
   });
 }

使用 someHTML.html 文件如此:

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

(注意:我不知道为什么我需要 setTimeout 但是由于某种原因,我会这样做,也许你的答案不会需要它。)

(note: I don't know why I need the setTimeout but for some reason I do. Maybe your answer won't require it.)

推荐答案

我最近写了一个函数来导入CSS。

I recently wrote a function to import 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();

    });


};

这篇关于如何从一个js文件加载所有脚本,样式表和标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆