JQuery动态加载Javascript文件 [英] JQuery to load Javascript file dynamically
问题描述
我有一个非常大的javascript文件,我只想在用户点击某个按钮时加载。我使用jQuery作为我的框架。是否有内置方法或插件可以帮助我这样做?
I have a very large javascript file I would like to load only if the user clicks on a certain button. I am using jQuery as my framework. Is there a built-in method or plugin that will help me do this?
更多细节:
我有一个添加注释按钮,应该加载TinyMCE javascript文件(我把所有TinyMCE的东西都煮成了一个单个JS文件),然后调用tinyMCE.init(...)。
Some more detail: I have a "Add Comment" button that should load the TinyMCE javascript file (I've boiled all the TinyMCE stuff down to a single JS file), then call tinyMCE.init(...).
我不想在初始页面加载时加载它,因为不是每个人都会点击添加评论。
I don't want to load this at the initial page load because not everyone will click "Add Comment".
我知道我可以做:
$("#addComment").click(function(e) { document.write("<script...") });
但是有更好的/封装方式吗?
but is there a better/encapsulated way?
推荐答案
是的,使用 getScript 而不是文档。写 - 它甚至会在文件加载后允许回调。
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
你可能想要检查TinyMCE是否已定义,但是在包含它之前(后续调用'添加评论')所以代码看起来像这样:
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
假设你只需要打电话给 init
它曾经,那就是。如果没有,你可以从这里弄明白:)
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
这篇关于JQuery动态加载Javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!