远程JavaScript加载后执行本地的Javascript? [英] Execute local Javascript after remote javascript loads?

查看:153
本文介绍了远程JavaScript加载后执行本地的Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,我使用jQuery / AJAX拉下HTML / JS的一大块从另一个组成部分,其注入的页面。这HTML引用的其他JS文件,我需要之前,我跑我的JavaScript加载这些引用的JS文件。

I have a page where I am using jquery/ajax to pull down a chunk of HTML/JS from another component and injecting it into the page. That HTML references additional JS files, and I need those referenced JS files to be loaded before I run my javascript.

的HTML / JS正被注入看起来是这样的:

The HTML/JS that is being injected looks something like this:

<script type="text/javascript" src="http://myserver/js/ABunchOfStuff.js"></script>
<div>
   blah blah blah
</div>
<script type="text/javascript">
    //"sourceList" is defined in the ABunchOfStuff.js above, but it's not available by the time this executes.  
    $("input#autocomplete").autocomplete({
        source: sourceList,
        minLength: 2
    });
</script>

通常情况下,我只想钩到一个窗口加载事件或$(文件)。就绪()或什么,但在这种情况下,窗口和文件都已经被完全加载,而现在我们增加后的附加内容事实上,

Normally I would just hook into a window load event or a $(document).ready() or whatever, but in this case the window and document have already been completely loaded, and now we're adding additional content after the fact.

一个方法可行办法是把一个递归setTimeout调用中,将继续射击,直到referneced JavaScript是可用的,但是这是pretty的难看。

One possiblity would be to put a recursive setTimeout call in that would keep firing until the referneced javascript was available, but that's pretty ugly.

那么,有没有干净的方式来捕获一个引用的JavaScript的事件已加载,并且在那个时间执行code?

So is there any clean way to trap the event of a referenced javascript has been loaded and to execute code at that time?

感谢

推荐答案

您也可以使用 getScript加入 并做你的自动完成的成功回调:

You can also use getScript and do your autoComplete in the success callback:

jQuery.getScript( 'http://myserver/js/ABunchOfStuff.js', function(data, textStatus) {
        $("input#autocomplete").autocomplete({
            source: sourceList,
            minLength: 2
        });
} );

这篇关于远程JavaScript加载后执行本地的Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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