jQuery getScript()vs document.createElement('script') [英] jQuery getScript() vs document.createElement('script')

查看:137
本文介绍了jQuery getScript()vs document.createElement('script')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这两种方法都正确加载脚本,并且在使用脚本之前等待适当的时间(和/或使用回调),这些方法之间的主要区别是什么。

Assuming that both of these approaches load the script properly, and that I wait the appropriate amount of time before using the script (and/or use a callback), what are the major differences between these approaches.

注意:我理解第一个使用jQuery(这是一个更大的下载等)。我真正感兴趣的是这些方法的影响。是否将脚本放在与另一个不同的范围内?等等。

jQuery:

function loadScript() {
    $.getScript('http://www.mydomain/myscript.js');
}

附加到正文:

function loadScript() {
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://www.mydomain/myscript.js';
   script.async = true;
   document.body.appendChild(script);
}

追加头:

function loadScript() {
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://www.mydomain/myscript.js';
   script.async = true;
   head.appendChild(script);
}


推荐答案

jQuery追加 script 元素到 head 如果存在,或者到 document 元素。引擎盖下代码类似。最终结果将是相同的:两种方法都在全局范围内执行新代码。

jQuery appends the script element to head if present, or to document element otherwise. Under the hood the code is similar. The final result will be the same: both approaches execute new code in the global scope.

这篇关于jQuery getScript()vs document.createElement('script')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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