这是一个非常简单的脚本,应该加载jQuery.我可以在Firebug Scripts选项卡中看到jquery正在加载,但是当我尝试使用它时,我得到'$ is not defined'错误.任何人都可以帮我理解什么是错的?
//function to add scripts
function include(file)
{
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
script.defer = true;
document.getElementsByTagName('head').item(0).appendChild(script);
}
//add jQuery
include('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
//See if jQuery is working
$(document).ready(function() {
$('#internal').show();
})
////////////
//RETURNS: "$ is not defined $(document).ready(function() {"
Run Code Online (Sandbox Code Playgroud)
奇怪的是,如果不尝试在同一个脚本中使用jQuery而我加载另一个使用jQuery的js文件它确实有效
//function to add scripts
function include(file)
{
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
script.defer = true;
document.getElementsByTagName('head').item(0).appendChild(script);
}
//add jQuery
include('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
//add my custom script that wants to use jQuery
include('scripts/testScript.js')
Run Code Online (Sandbox Code Playgroud)
testScript.js
$(document).ready(function() {
$('#external').show();
})
Run Code Online (Sandbox Code Playgroud)
我对此表示感谢.
我猜这是因为浏览器只会在完成执行当前文件后添加的脚本节点中执行JavaScript.
浏览器将在一个线程中执行您当前的脚本.当它到达脚本的末尾时,它会执行DOM中的下一个脚本.它无法停止通过一个脚本跳转到下一个脚本.
您可能想看一下Google的JavaScript加载器.有效的方法是告诉它加载外部js文件,并注册一个回调函数,以便在加载该文件时执行.
您可以使用回调来执行此操作,因为回调中的代码将仅在浏览器完成当前文件的执行并移至下一个文件后执行.但你不能做的是让浏览器动态地从一个js文件切换到另一个js文件(即它首次执行文件的内容时).