【问题标题】:How to load css and js如何加载css和js
【发布时间】:2015-02-09 12:07:17
【问题描述】:

我的js脚本将页面的一部分加载到另一个页面,但是css和js没有加载(。

例如: 第 1 页包含加载第 2 页的 js。第 2 页包含类似 . 第2页成功加载到第1页,但没有任何css或js?我包括在内。

这是加载页面的代码:

var newdiv = $('<div id="blah"/>');
$('body').append(newdiv);
$('#blah').load('http://paht/to/file.php', function(){...

这是加载页面的代码:

<link rel = "stylesheet" href = "http://path/to/file.css">
<div id="id" class="class">
....
</div>
<script src="http://path/to/js.js"></script>

附:如果我直接复制 css 和 js 而不是 &lt;link href="..."&gt;&lt;script src="..."&gt;,效果很好。
第 1 页包含我无法更改的脚本。我只能更改第 2 页。如果我直接编写 css 和 js - 它工作正常,但如果我尝试在 css 和 js 上编写链接 - 它会崩溃。

http://i.stack.imgur.com/KUjmk.jpg

【问题讨论】:

  • 将所有脚本加载到第 1 页不是解决方案吗?
  • 能否包含用于加载第 2 页的代码?
  • js script loads the part of page - 没有关于加载 js 或 css 的内容。
  • 请说明您使用的加载另一个页面的技术:是框架,还是动态DOM注入+Ajax调用?

标签: javascript css load


【解决方案1】:

您的文件 css 和 js 未加载,因为 load 使用 .innerHTML 属性解析检索到的文档并将其插入到当前文档中。

要加载脚本,您应该自己在文档的&lt;head&gt; 中创建&lt;script&gt;&lt;link&gt; 元素。

试试$.getScript();函数

$('#blah').load('http://paht/to/file.php', function(){
    $.getScript("path of your script js");
    ...

对于css文件:

$('<link/>', {
    rel: 'stylesheet',
    type: 'text/css',
    href: 'path_to_the.css'
}).appendTo('head');

参考:

http://api.jquery.com/load/

【讨论】:

  • 第 1 页包含我无法更改的脚本。我只能更改第 2 页。如果我直接编写 css 和 js - 它工作正常,但如果我尝试在 css 和 js 上编写链接 - 它会崩溃。
  • 我编辑了我的答案。您的 html 结构在加载后由 2 个标签“head”组成? (第 1 页头和第 2 页头)
  • 不,第 2 页只包含几个 div。第 2 页没有标题。
  • 我画了一幅画。祝你有美好的一天!
  • 你喜欢我的画吗?
猜你喜欢
  • 2014-09-05
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 2021-06-01
  • 2017-03-08
相关资源
最近更新 更多