等待动态加载的脚本 [英] Waiting for dynamically loaded script

查看:118
本文介绍了等待动态加载的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的页面正文中,我需要将此代码作为AJAX调用的结果插入:

 < p>加载jQuery< / p> 
< script type ='text / javascript'src ='scripts / jquery / core / jquery-1.4.4.js'>< / script>
< p>使用jQuery< / p>
< script type ='text / javascript'>
$ .ajax({
...
});
< / script>

我无法使用 $。load()因为文档已经加载,所以事件不会触发。



这是否安全?如果没有,我如何确保jquery脚本在我的自定义生成代码执行之前已经加载。

安全。历史上,< script> 标记是完全阻止的,因此第二个< script> 标记无法遇到之前,前者已完成解析/删除。唯一的问题可能是现代浏览器倾向于加载脚本异步和延期。所以要确保订单是正确的,请像这样使用它:

 < p>加载jQuery< / p> 
< script type ='text / javascript'async = false defer = false src ='scripts / jquery / core / jquery-1.4.4.js'>< / script>
< p>使用jQuery< / p>
< script type ='text / javascript'>
$ .ajax({
...
});
< / script>

然而,使用动态脚本标记插入而不是将其作为HTML字符串插入DOM。将是相同的故事

  var scr = document.createElement('script'),
head = document.head || document.getElementsByTagName(头)[0];
scr.src ='scripts / jquery / core / jquery-1.4.4.js';
scr.async = false; //可选

head.insertBefore(scr,head.firstChild);


In my page body, I need to insert this code as the result of an AJAX call:

    <p>Loading jQuery</p>
    <script type='text/javascript' src='scripts/jquery/core/jquery-1.4.4.js'></script>
    <p>Using jQuery</p>
    <script type='text/javascript'>
        $.ajax({
            ...
        });
    </script>

I can't use $.load() since the document has already loaded, so the event doesn't fire.

Is this safe? If not, how do I make sure the jquery script has loaded before my custom, generated code is executed.

解决方案

It is pretty safe. Historically, <script> tags are full blocking, hence the second <script> tag can't get encountered befored the former has finished parsing/excuting. Only problem might be that "modern" browsers tend to load scripts asynchronously and deferred. So to make sure order is correct, use it like this:

<p>Loading jQuery</p>
<script type='text/javascript' async=false defer=false src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
    $.ajax({
        ...
    });
</script>

However, it's probably a better idea it use dynamic script tag insertion instead of pushing this as HTML string into the DOM. Would be the same story

var scr  = document.createElement('script'),
    head = document.head || document.getElementsByTagName('head')[0];
    scr.src = 'scripts/jquery/core/jquery-1.4.4.js';
    scr.async = false; // optionally

head.insertBefore(scr, head.firstChild);

这篇关于等待动态加载的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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