JS:外部加载

JS: external loading

本文关键字:加载 外部 JS      更新时间:2023-09-26

我有很多页面在不同的领域,需要包括一些。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>

这是最好的方法吗?是否存在我没有考虑到的跨域或跨站攻击安全问题?

谢谢

您可以导入单个文件并使用资源加载器来管理依赖关系,而不是使用外部资源来管理代码加载。而不是让外部脚本执行代码(触发同源策略),您可以在一个地方管理所有内容,并避免任何跨域问题。

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                                                      */
}, ... ]);