我希望使用JavaScript异步加载外部jQuery文件,然后能够调用从外部JavaScript加载的函数。我将我的JS文件包含在html的底部,就在</html>之前。jQuery代码就在我的代码之前。
我在尝试这个:
(function(){
$(document).ready(function() {
obj.init();
});
var obj = {
init:function(){
$.ajax({
url: 'http://domain.com/script.js',
dataType: 'script',
success: function() {
obj.dostuff();
}
});
},
dostuff:function() {
// ...do stuff
}
}
window.obj = obj;
})();Chrome JavaScript控制台正在报告如下:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
我试图将所有JS保存在一个文件中,全部保存在对象(类和函数样式)中,然后从$(document).ready();中调用每个类(一个$(document).ready();函数)。
我在这里做错什么了..?
发布于 2014-12-17 11:29:55
可以使用以下方法加载脚本
var scriptElement = document.createElement('script');
scriptElement.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(scriptElement);然后,您可以开始使用jQuery或任何已加载的库。
或者类似的东西
function loadMyScript() {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-latest.min.js";
document.body.appendChild(script);
}
window.onload = loadMyScript;更新:
(function(app, $, undefined) {
//public
app.init = function() {
var url = "//code.jquery.com/color/jquery.color.js";
$.getScript(url, function() {
doStuff();
});
};
//private
var doStuff = function() {
$(".block")
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000)
.delay(500)
.animate({
backgroundColor: "olive"
}, 1000)
.delay(500)
.animate({
backgroundColor: "#00f"
}, 1000);
};
}(window.app = window.app || {}, jQuery));
window.onload = app.init;这是JsBin:http://jsbin.com/lumapubozu/1/edit?html,js,output
谷歌地图更新
您只需在链接'callback=app.loadMap'中说明它是您的回调。
(function(app) {
app.loadMap = function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
};
app.loadGoogleMapsScript = function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=app.loadMap';
document.body.appendChild(script);
};
}(window.app = window.app || {}));
window.onload = app.loadGoogleMapsScript;JsBin:http://jsbin.com/wigoxarayu/1/edit?js,output
https://stackoverflow.com/questions/27524505
复制相似问题