2017-12-30 23 views
0

5 초 페이지로드 후에 js 링크를로드하려고합니다. 내 페이지가로드되면 js 링크가 작동합니다. 페이지로드는 다음 오초 후이 링크가 작동 될 것입니다 때페이지로드 후 js 링크를로드하려고 시도합니다.

내 링크는

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script> 

입니다.

+0

은 당신이 뭔가를 시도했다 : 당신이 할 수있는 원하든

은의 setTimeout와 스크립트 요소를 삽입입니까? –

+0

왜 그 이유가 무엇입니까? – julekgwa

답변

0

당신은 DOM에 스크립트 요소를 추가 할 수 있습니다. 보세요 here.

setTimeout(function(){ 
    var script = document.createElement('script'); 
    script.onload = function() { 
     //do stuff when the script is loaded 
    }; 
    script.src = "//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"; 
    document.head.appendChild(script); //or something of the likes 
}, 5000); 
0

스크립트 태그에 defer 옵션을 사용할 수 있습니다.

<script defer src="..."></script> 

이 옵션을 사용하면 스크립트 다운로드/실행이 html 구문 분석을 방해하지 않습니다.

Here 다른 옵션을 볼 수 있습니다.

1

당신은 promises를 사용하여이 같은 것을 사용할 수 있습니다

// Make a function to return a promise for the sleep duration 
function sleep(ms) 
{ 
    return new Promise(resolve => setTimeout(resolve, ms)); 
} 

// make a function to handle the sleep 
async function loadNewScript(seconds, src) 
{ 
    await sleep(seconds * 1000); // This is 5 seconds (time in miliseconds) 
    getScript(src); 
} 

// make a function to get the script 
function getScript(src) 
{ 
    return new Promise(function (resolve, reject) 
    { 
     var s; 
     s = document.createElement('script'); 
     s.src = src; 
     s.onload = resolve; 
     s.onerror = reject; 
     document.head.appendChild(s); 
    }); 
} 

// And then just call it on pageload (this is not full page load, only DOM) 
document.addEventListener("DOMContentLoaded", function() 
{ 
    // loadNewScript(seconds, src) 
    loadNewScript(5, "http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"); 
});