브라우저로드 시간에 가장 적합한 솔루션은 서버 쪽 스크립트를 사용하여 모두 하나의 큰 .js 파일로 결합하는 것입니다. 최종 버전을 gzip/minify해야합니다. 단일 요청 - 좋고 간결합니다.
DOM을 사용하여 <script>
태그를 만들고 src 속성을 <head>
에 추가 할 수 있습니다. 해당 기능이로드 될 때까지 기다릴 필요가 있으면 해당 스크립트 태그의 load
이벤트에서 나머지 자바 스크립트 파일을 호출 할 수 있습니다.
이 기능은 또한 각 onload
이벤트를 사용할 수 있습니다 기본적으로 내가 <head>
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
에 그, 같이 할 새로운 요소를 작성하고 첨부 $.getScript()
function loadScript(src, f) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
var done = false;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof f == 'function') f();
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
// example:
loadScript('/some-other-script.js', function() {
alert('finished loading');
finishSetup();
});
방금 Grunt 플러그인을 만들었습니다. 주 응용 프로그램에 사용되는 기능 만 포함합니다. https://github.com/mr-moon/grunt-contrib-resolve –