2015-03-02 59 views
0

我有一個動態加載的jQuery,在<head>元素將其插入腳本:jQuery的不可見後腳本元素動態地添加它

// pseudo code 

headElelement.insertBefore(script, firstChild); 

然而,這一呼籲後,我立即開始使用jQuery,但在那一刻它是不確定的。這怎麼可能?

+0

如果代碼你運行你的內心後插入後jQuery的一個'$(函數(){});'塊? – atmd 2015-03-02 08:46:51

+0

我只是運行這種代碼while(typeof jQuery ==='undefined'){ }它永遠運行 – Zed 2015-03-02 08:50:01

+0

請發佈相關的代碼,否則它只是猜測:你是什麼意思的僞代碼,你真的在HTML本身加載jquery,如' ...'?你在哪裏嘗試使用它,你說「在那個電話後立即」,所以在頭上? – Ariel 2015-03-02 08:55:09

回答

-1

如果你想發佈您的相關代碼,它會更容易;-)但不管怎麼說,這是做的一種可能的方式:

<html> 
<head> 
    <script type="text/javascript" src="path_to_js/jquery.js"></script> 
    <script type="text/javascript" src="path_to_js/your_js_code.js"></script> 
    ... 
</head>... 

,並在文件中your_js_code.js你必須:

... /* All your modules and functions here */ 

/* DOM loading ready */ 
$(document).ready(function() { 
    call_your_methods_here(); 
}); 

順便說一句,它通常是更好地在HTML中<body>,你的HTML開始顯示第一和用戶這樣的最後加載您的JS文件「看到」你的網頁速度更快,而JS代碼仍在加載。

0

這是因爲jQuery尚未完全加載。只有通過將事件處理程序附加到動態創建的腳本元素的onload事件,才能加載jQuery,如下所示,您可能需要執行jQuery代碼。

script.onload = function() { 
    // Put your jQuery code here. 
    console.log(jQuery); 
}; 

支持舊的瀏覽器像IE8及以下跨瀏覽器的解決方案:

script.onload = script.onreadystatechange = function(event) { 
    event = event || window.event; 
    if (event.type === "load" || (/loaded|complete/.test(script.readyState))) { 
     script.onload = script.onreadystatechange = null; 
     // Put your jQuery code here. 
     console.log(jQuery); 
    } 
};