JS:外部加载

时间:2011-09-27 15:51:28

标签: javascript jquery html

我在不同的域中有很多页面需要包含一些.js .css和html。我想“远程”更新包含的代码。

所以在那些我想要放置的静态页面中:

<script src="http://centraldomain.com/include.js" type="text/javascript"></script>

然后在该文件中执行:

document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><div id="results"></div>');

$('#result').load('http://domain.com/include-rest.html');

并在那个html中放置我想在这些页面中插入的所有html,例如:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/cupertino/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
some html without <head> or <body>

这是最好的方法吗?我没有考虑任何跨域或XSS攻击安全问题吗?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用资源加载程序来管理依赖项,而不是使用外部资源管理代码加载。您可以在一个地方管理所有内容,并在任何跨域问题上执行任务,而不是让外部脚本执行代码(跳过相同的原始策略)。

yepnope.js是一个有用的异步资源。您可以对您所在的任何站点使用test,导入必要的文件,然后测试您的站点以确定是否需要执行任何其他代码。

看看http://yepnopejs.com/ - 这是一个快速浏览。

yepnope([{
  test : /* boolean(ish) - Something truthy that you want to test             */,
  yep  : /* array (of strings) | string - The things to load if test is true  */,
  nope : /* array (of strings) | string - The things to load if test is false */,
  both : /* array (of strings) | string - Load everytime (sugar)              */,
  load : /* array (of strings) | string - Load everytime (sugar)              */,
  callback : /* function ( testResult, key ) | object { key : fn }            */,
  complete : /* function                                                      */
}, ... ]);