可能重複:負載JS加載
我已經包括jQuery的是這樣的:
function loadScript(loc){
var head = document.getElementsByTagName('head')[0];
var file = document.createElement('script');
file.src = loc;
file.type = "text/javascript";
head.appendChild(file)
}
loadScript("js/jquery.js")
現在,下一個腳本應加載相同的方式。但是如果在最後一行之後加載,我不能使用jQuery,因爲它可能無法完成加載。 那麼如何檢查,如果jQuery的加載完成了? 我可以做這樣的事情?:
while (typeof jQuery == 'undefined')
{
wait...
}
可能重複[如何檢查腳本元素加載事件跨瀏覽器沒有jQuery](http://stackoverflow.com/questions/12574549/how-to-check-the-script-element-load-event-accross -browser-without-jquery)或[動態腳本加載同步](http://stackoverflow.com/questions/774752/dynamic-script-loading-synchronization) – Bergi
不,你不能做那樣的事情。無法在JavaScript中忙於等待,因爲它不會終止並凍結瀏覽器。另外,您永遠無法確定該腳本是否聲明瞭一個名爲「jQuery」的變量。 – Bergi
檢查此相關的答案:** [加載排序動態添加的腳本標記](http://stackoverflow.com/a/38840724/2247494)** – jherax