簡體   English   中英

Java在onReady之后加載外部框架

[英]Javascript load external frameworks after onReady

通常,您在HTML源代碼的head元素中擁有所有框架(腳本和CSS),並且在渲染頁面時將加載它們。 例如,我想加載jQuery和boostrap,它看起來像這樣:

<html>
  <head>
    <script src="jquery.min.js"></script>
    <script src="bootstrap.min.js"></script>
    <link href="jquery.min.css"\>
    <link href="bootstrap.min.css"\>
  </head>
</html>

但是,設想一種情況,您從一開始就只加載了jQuery,並且想要執行諸如單擊按鈕之類的操作,並且需要一些框架功能(例如,引導程序提供的功能),則需要在單擊后立即加載它們。

以我的理解,這並不像聽起來那樣容易,因為在渲染完側面之后需要加載的框架需要執行OnReady調用。 有沒有簡單的方法可以做到這一點?

親切的問候,馬呂斯

“設想一種情況,您從一開始就只加載jQuery,並且想要執行諸如單擊按鈕之類的操作,並且需要一些框架功能(例如,引導程序提供的功能),則需要在單擊后立即加載它們。”

您所描述的是依賴項的延遲加載

RequireJS做得很好。

如果您想這樣做以提高用戶的頁面加載性能,則可以簡單地使用標記的async屬性,如下所示:

<script src="jquery.min.js" async></script>

https://css-tricks.com/thinking-async/上了解有關異步加載的更多信息。

如果您在某個事件后還有其他原因要加載js,請使用以下方法:

function loadJavaScript(url)
{
    var s = document.createElement('script');
    s.setAttribute('src', url);
    s.setAttribute('async',true);
    document.head.appendChild(s);
}

您可以將腳本的地址作為loadJavaScript('https://ajax.googleapis.com/ajax/libs/dojo/1.12.2/dojo/dojo.js')傳遞

UPDATE

在腳本加載時使用onload處理程序調用函數:

 $(document).ready(function() { $('#test').click(function() { console.log("oO"); loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'); loadJavaScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.js',function(){ $('.selectpicker').selectpicker('refresh'); }); }); }); function loadCss(url,fn) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); } function loadJavaScript(url) { var s = document.createElement('script'); s.setAttribute('src', url); s.setAttribute('async',false); if(typeof(fn) == "function") { fn(); } document.head.appendChild(s); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="test" type="button" class="btn btn-primary">Basic</button> <select class="selectpicker"> <option>1</option> </select> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM