在appendChild上没有加载Jquery脚本 [英] Jquery script is not loaded, on appendChild

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

问题描述

我正在使用此代码动态加载我的脚本文件,

I am loading my script files dynamically using this code,

<script type="text/javascript">
  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.src = '../static/js/jquery.js';
  document.getElementsByClassName('container')[0].appendChild(newscript);

  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.src = '../static/js/report_app.js';
  document.getElementsByClassName('container')[0].appendChild(newscript);

</script>

它抛出错误,

Reference error: $ is not defined 

in report_app.js

我想, jquery.js 必须加载脚本当正在解析下一个文件 report_app.js 时进入DOM。

I thought, jquery.js script must be loaded into the DOM when the next file, report_app.js is being parsed.

但错误显示, jquery.js 未执行。如何确保在运行下一个脚本文件之前加载一个脚本文件?

But the error shows, jquery.js is not executed. How to ensure one script file is loaded before running the next one?

推荐答案

这是因为脚本是异步添加的,你可以使用onload回调

It is because the script is added asynchronously, you can use the onload callback

function addScript(path, callback) {
    var newscript = document.createElement('script');
    newscript.type = 'text/javascript';
    newscript.src = path;
    newscript.onload = callback;
    document.body.appendChild(newscript);

}

addScript('http://code.jquery.com/jquery-1.11.2.js', function () {
    addScript('../static/js/report_app.js');
})

演示: 小提琴

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

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