在使用jquery之前动态加载jquery [英] Load jquery dynamically before using jquery
问题描述
我的脚本将在第三方网站中用作小部件,因此我不了解jquery的加载以及在第三方端是否加载了jquery的版本.
My script will be using as widget in third-party website so i don't aware about jquery loaded and which version of jquery loaded or not at third-party end.
因此,在加载下面的脚本之前,我想检查是否在dom准备好之后已经加载了最新的jquery 1.11.1(如果没有),那么我想加载最新的jquery,并在脚本下面运行.
So Before loading below script i want to check is there already latest jquery 1.11.1 loaded after dom ready if not then i want to load the jquery latest and run below script.
script.js
script.js
var $ = jQuery.noConflict( true );
(function( $ ) {
$(document).ready(function() {
alert("Document Ready ");
});
})($jy);
修改1
var addNewJQuery = function() {
(function( $ ) {
$jy = $;
var invokeOriginalScript;
$(document).ready(function() {
......my code here.....
}):
})(jQuery);
}
推荐答案
不确定这是否对您有用,但看起来像在工作.
Not sure if this is working for you, but it looks like it is working.
加载第二个jQuery文件后,可能需要从标头中删除其他脚本.但这似乎可以同时加载两个脚本.
Maybe you need to remove the other script from your header after you loaded the second jQuery file. But it seems to work with both scripts loaded.
我还添加了一个检查,是否可以完全加载jQuery,否则将加载jQuery.
I've also added a check if jQuery is loaded at all, if not it will load jQuery.
您还可以在此小提琴中找到相同的代码.
You can also find the same code in this fiddle.
var addNewJQuery = function() {
//var jQ = jQuery.noConflict(true);
(function ($) {
$(document).ready(function () {
alert("You are now running jQuery version: " + $.fn.jquery);
});
})(jQuery);
};
if ( typeof jQuery === 'undefined' ) {
alert('no jQuery loaded');
//throw new Error("Something went badly wrong!"); // now you could load jQuery
loadScript('https://code.jquery.com/jquery-1.11.2.js', addNewJQuery);
}
if ($.fn.jquery !== '1.11.2') {
console.log('detected other jQuery version: ', $.fn.jquery);
loadScript('https://code.jquery.com/jquery-1.11.2.js', addNewJQuery);
}
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
这篇关于在使用jquery之前动态加载jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!