document.write를 포함 할 수있는 src로 스크립트 태그를 동적으로 추가
웹 페이지에 스크립트 태그를 동적으로 포함하고 싶지만 src를 제어 할 수 없으므로 src = "source.js"는 다음과 같습니다.
document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')
이제는 보통
<script type="text/javascript" src="source.js"></script>
머리에 잘 작동하지만 innerHTML과 같은 것을 사용하여 source.js를 동적으로 추가 할 수있는 다른 방법이 있습니까?
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);
다음 document.createElement()
과 같은 기능을 사용할 수 있습니다 .
function addScript( src ) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
}
이 onload
스크립트가 성공적으로로드되면 호출 할 수있는 기능은 :
function addScript( src,callback) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
s.onload=callback;
document.body.appendChild( s );
}
여러 스크립트를로드하기 위해 작성한 멋진 작은 스크립트 :
function scriptLoader(scripts, callback) {
var count = scripts.length;
function urlCallback(url) {
return function () {
console.log(url + ' was loaded (' + --count + ' more scripts remaining).');
if (count < 1) {
callback();
}
};
}
function loadScript(url) {
var s = document.createElement('script');
s.setAttribute('src', url);
s.onload = urlCallback(url);
document.head.appendChild(s);
}
for (var script of scripts) {
loadScript(script);
}
};
용법:
scriptLoader(['a.js','b.js'], function() {
// use code from a.js or b.js
});
다음 코드 스 니펫을 시도 할 수 있습니다.
function addScript(attribute, text, callback) {
var s = document.createElement('script');
for (var attr in attribute) {
s.setAttribute(attr, attribute[attr] ? attribute[attr] : null)
}
s.innerHTML = text;
s.onload = callback;
document.body.appendChild(s);
}
addScript({
src: 'https://www.google.com',
type: 'text/javascript',
async: null
}, '<div>innerHTML</div>', function(){});
이 작업을 수행하는 유일한 방법은 document.write
페이지 하단에 요소를 추가하는 자체 기능 으로 바꾸는 것입니다. jQuery를 사용하면 매우 간단합니다.
document.write = function(htmlToWrite) {
$(htmlToWrite).appendTo('body');
}
If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite
segments. Maybe something like this:
document.write = (function() {
var buffer = "";
var timer;
return function(htmlPieceToWrite) {
buffer += htmlPieceToWrite;
clearTimeout(timer);
timer = setTimeout(function() {
$(buffer).appendTo('body');
buffer = "";
}, 0)
}
})()
Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.
var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);
You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.
Inserting Dynamic Javascript the right way
I tried it by recursively appending each script
Note If your scripts are dependent one after other, then position will need to be in sync.
Major Dependency should be in last in array so that initial scripts can use it
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']
let count = 0
const recursivelyAddScript = (script, cb) => {
const el = document.createElement('script')
el.src = script
if(count < scripts.length) {
count ++
el.onload = recursivelyAddScript(scripts[count])
document.body.appendChild(el)
} else {
console.log('All script loaded')
return
}
}
recursivelyAddScript(scripts[count])
'IT story' 카테고리의 다른 글
루비에서 특정 변수가 해시인지 아니면 배열인지를 간단하고 우아한 방법은 무엇입니까? (0) | 2020.07.07 |
---|---|
NSArray 요소를 NSString에 결합하는 방법은 무엇입니까? (0) | 2020.07.07 |
지원 라이브러리가있는 FloatingActionButton 예제 (0) | 2020.07.07 |
XML에서 CDATA 엔드 토큰을 이스케이프 처리하는 방법이 있습니까? (0) | 2020.07.07 |
팬더 데이터 프레임에서 행의 하위 집합 수정 (0) | 2020.07.07 |