是否有可能加载新的JavaScript文件使用AJAX? [英] Is it possible to load new Javascript files with AJAX?

查看:112
本文介绍了是否有可能加载新的JavaScript文件使用AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个新的AJAX供电的网站有不同的部分。各部分都需要一套新的Javascript函数来运行。我不想在一开始加载每个脚本,因为可能有相当多的。

I'm building a new AJAX powered website with distinct sections. Each section requires a new set of Javascript functions to run. I'd rather not load every script at the start, as there might be quite a few.

有没有办法使用AJAX来加载新的脚本,并删除​​旧的(这样才能确保有类似的变量名或函数签名不存在兼容性问题)。

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

感谢

修改 - jQuery是很好,它没有被老同学的Javascript

Edit - JQuery is fine, it doesn't have to be old school Javascript

推荐答案

三样东西:

1)是的,你可以装载新的脚本。你甚至不需要AJAX的XHR意义 - 只需在你网页中的脚本标记动态。 jQuery提供$ .getScript()为这样的事情,或者你可以简单地创建一个脚本元素,并将其添加到您的文档的头部。有一个极大的例子,如果你google一下。

1) Yes, you can load new scripts. You don't even need AJAX in the XHR sense - simply include the script tag in your page dynamically. jQuery provides $.getScript() for things like this, or you can simply create a script element and append it to the head of your document. There are a gazillion examples if you google it.

2)关于删除旧的(和冲突等)。假设你已经对这些函数名的控制,只是命名空间进行正确:

2) Regarding removing the old (and conflicts, etc). Assuming you have control over these function names, just namespace them properly:

window.myapp = {};
window.myapp.mysection = {};
window.myapp.myothersection = {};
window.myapp.mysection.myfunction = function(){}

那你不用担心冲突。

Then you don't have to worry about conflicts.

3)注意此点。加载所有这些脚本的开销按需可能不仅仅是COM pressing和装载一次性整个事情反正。

3) Be careful about this. The overhead of loading all those scripts on-demand might be more than just compressing and loading the whole thing in one shot anyway.

这篇关于是否有可能加载新的JavaScript文件使用AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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