3

有没有办法等到 jquery 库加载完毕,直到我们执行其他外部 javascript 文件,所以等待它完全加载:

<script type="text/javascript"  src="jquery-1.7.2.js"></script>

然后加载其他文件,例如:

<script type="text/javascript"  src="campaign_winter_2013/bg_outerwear/js/main.js"></script>
<script type="text/javascript"  src="campaign_winter_2013/bg_outerwear/js/mousePosSlide.js"></script>

问题是我在平台中集成代码并且 jquery 库在我的脚本之前加载。

4

2 回答 2

6

您可以先加载 jquery 库,然后调用 JS 文件中定义的方法。以下代码对我有用。

<body> 

function loadJQuery(){

var waitForLoad = function () {
    if (typeof jQuery != "undefined") {
        console.log("jquery loaded..");
        // invoke any methods defined in your JS files to begin execution       
    } else {
        console.log("jquery not loaded..");
        window.setTimeout(waitForLoad, 500);
    }
 };
 window.setTimeout(waitForLoad, 500);   
}

window.onload = loadJQuery;

</body>
于 2014-09-23T17:31:49.800 回答
1

检查这个:

https://jsfiddle.net/neohunter/ey2pqt5z/

它将创建一个假的 jQuery 对象,允许您使用 jquery 的 onload 方法,它们将在 jquery 加载后立即执行。

这并不完美。

// This have to be on <HEAD> preferibly inline
var delayed_jquery = [];
jQuery = function() {
  if (typeof arguments[0] == "function") {
    jQuery(document).ready(arguments[0]);
  } else {
    return {
      ready: function(fn) {
        console.log("registering function");
        delayed_jquery.push(fn);
      }
    }
  }
};
$ = jQuery;
var waitForLoad = function() {
  if (typeof jQuery.fn != "undefined") {
    console.log("jquery loaded!!!");
    for (k in delayed_jquery) {
      delayed_jquery[k]();
    }
  } else {
    console.log("jquery not loaded..");
    window.setTimeout(waitForLoad, 500);
  }
};
window.setTimeout(waitForLoad, 500);
// end



// now lets use jQuery (the fake version)
jQuery(document).ready(function() {
  alert('Jquery now exists!');
});

jQuery(function() {
  alert('Jquery now exists, this is using an alternative call');
})

// And lets load the real jquery after 3 seconds..
window.setTimeout(function() {
  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.async = true;
  newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);
}, 3000);

于 2016-01-07T15:01:23.487 回答