我有一个应用程序可以检查当前加载的脚本中是否有 jQuery。 如果没有,我用 getScript 检索它并加载一个函数,该函数基本上检索通过 $.getJSON 序列化为 json 的 html/js,然后执行它:
if (typeof jQuery == 'undefined') {
if (typeof $ == 'function') {
thisPageUsingOtherJSLibrary = true;
}
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0];
done = false;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
};
getScript(AbsURL + '/scripts/jquery/jquery-1.9.1.min.js', function () {
if (typeof jQuery !== 'undefined') {
if (!thisPageUsingOtherJSLibrary) {
jQuery(document).ready(function ($) {
MyFunction($);
});
} else {
...
}
}
});
}
function MyFunction($) {
$.getJSON(AbsURL + "/widget/Init.aspx?" + queryString + "&callback=?", function (html) {
JsonToHtml(html);
});
function JsonToHtml(html) {
var items = [];
$.each(html, function (key, val) {
items.push(val);
});
$('body').prepend(items.join(''));
}
}
事实是:如果我在加载主页时有 jQuery,则会执行加载(反序列化)的脚本,否则它会添加到正文中,但不会执行任何操作。
我在这里缺少哪一步?
问题是加载脚本的执行。 这是执行:
<script type="text/javascript">console.log("ciaopollo");</script>
这不是:
<script type="text/javascript">(function (w, d) { var loader = function () { var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0]; s.src = "http://cdn.iubenda.com/iubenda.js"; tag.parentNode.insertBefore(s, tag); }; if (w.addEventListener) { w.addEventListener("load", loader, false); } else if (w.attachEvent) { w.attachEvent("onload", loader); } else { w.onload = loader; } })(window, document);</script>
最佳答案
您可以使用deferred.done()来自$get.JSON() 。由于 $get.JSON()
是异步的并且实现了 Promise 接口(interface),因此您可以获得延迟属性,例如 .done()
、.error()
等
因此,请确保响应成功,然后执行下一步操作,否则处理错误。
JQuery 文档中的示例:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
或者,如果您需要在 critical render path 之前获取脚本,则可以通过将其嵌入到 head 中来加载脚本。 ,一些开发人员使用此策略来防止 javascript 阻止页面加载。以下示例是获取网络字体的代码摘录:
// this is just another way to create '<script src...'> and
// a method used by placing it in <head></head> so its processed
// before critical render path.
(function() {
document.getElementsByTagName("html")[0].className += " wf-loading";
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
希望这有帮助。
针对格式原因回复以下评论: 尝试以下操作:
// optional reference to d, declare var _d;
$.getJSON( file, query , function( d ) {
// do nothing or _d = d;
})
.done(function( d ) {
// call fn(d)
});
关于javascript - 如果我动态加载(在它之前)jQuery,为什么 jQuery 无法执行加载的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055021/