document.write의 대안은 무엇입니까?
튜토리얼에서 나는 document.write
. 이제 나는 이것이 많은 사람들에게 눈살을 찌푸리고 있다는 것을 이해합니다. 나는 시도 print()
했지만 문자 그대로 프린터로 보냅니다.
그렇다면 내가 사용해야 할 대안은 무엇이며 왜 사용하지 않아야 document.write
합니까? w3schools와 MDN 모두 document.write
.
권장되는 대안으로 DOM 조작 을 document.write
사용하여 DOM 에 노드 요소를 직접 쿼리하고 추가 할 수 있습니다 .
HTML이 대체되는 이유는 악의적 인 JavaScript 함수 때문입니다 : document.write()
.
확실히 "나쁜 형태"입니다. 페이지로드시 사용하는 경우에만 웹 페이지에서 작동합니다. 런타임 중에 사용하면 전체 문서가 입력으로 바뀝니다. 그리고 엄격한 XHTML 구조로 적용하는 경우 유효한 코드도 아닙니다.
문제 :
document.write
문서 스트림에 씁니다. 호출document.write
자동 폐쇄 (또는로드) 문서에 호출document.open
문서를 삭제합니다.
- MDN에서 인용
document.write()
두 명의 henchmen, document.open()
및 document.close()
. HTML 문서가로드 될 때 문서는 "열려"있습니다. 문서로드가 완료되면 문서가 "닫혔습니다". document.write()
이 시점에서 사용하면 전체 (닫힌) HTML 문서가 지워지고 새 (열린) 문서로 바뀝니다. 이것은 귀하의 웹 페이지가 처음부터 지워지고 새 페이지 작성을 시작했음을 의미합니다.
document.write()
브라우저의 성능이 저하되는 원인이 된다고 생각 합니다 (내가 틀렸다면 수정).
예 :
이 예제는 페이지가로드 된 후 HTML 문서에 출력을 기록합니다 . document.write()
"종료"버튼을 누르면 악의적 인 힘이 문서 전체를 지우는 것을 지켜보십시오 .
I am an ordinary HTML page. I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>
me!
대안 :
.innerHTML
이것은 훌륭한 대안이지만이 속성은 텍스트를 넣을 요소에 첨부되어야합니다.
예: document.getElementById('output1').innerHTML = 'Some text!';
.createTextNode()
W3C에서 권장하는 대안 입니다.
예: var para = document.createElement('p'); para.appendChild(document.createTextNode('Hello, '));
참고 : 이로 인해 성능이 약간 저하되는 것으로 알려져 있습니다 (보다 느림 .innerHTML
). .innerHTML
대신 사용 하는 것이 좋습니다 .
.innerHTML
대안이 있는 예 :
I am an ordinary HTML page.
I am innocent, and purely for informational purposes.
Please do not
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>
me!
<p id="output1"></p>
다음은 document.write를 제자리에서 대체해야하는 코드입니다.
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
성능 문제 (동기식 DOM 주입 및 평가) document.write
로 인해 사용 이 매우 싫증이 났지만 , 필요에 따라 스크립트 태그를 주입하는 데 사용 하는 경우 실제 1 : 1 대안 도 없다는 것을 여기에 메모 만 남겨 두십시오 .document.write
이를 피할 수있는 좋은 방법이 많이 있지만 (예 : 종속성 체인을 관리하는 RequireJS 와 같은 스크립트 로더 ) 더 침습적이기 때문에 사이트 / 애플리케이션 전체 에서 가장 잘 사용 됩니다 .
질문은 실제로하려는 작업에 따라 다릅니다.
일반적으로, 대신 일을 document.write
당신이 사용할 수있는 someElement.innerHTML
더 나은 또는 document.createElement
와 함께 someElement.appendChild
.
jQuery와 같은 라이브러리를 사용하고 거기에있는 수정 기능을 사용하는 것도 고려할 수 있습니다. http://api.jquery.com/category/manipulation/
아마도 가장 정확하고 직접적인 대체 인 insertAdjacentHTML 일 것 입니다.
getElementById () 또는 getElementsByName ()을 사용하여 특정 요소에 액세스 한 다음 innerHTML 속성을 사용합니다.
<html>
<body>
<div id="myDiv1"></div>
<div id="myDiv2"></div>
</body>
<script type="text/javascript">
var myDiv1 = document.getElementById("myDiv1");
var myDiv2 = document.getElementById("myDiv2");
myDiv1.innerHTML = "<b>Content of 1st DIV</b>";
myDiv2.innerHTML = "<i>Content of second DIV element</i>";
</script>
</html>
I fail to see the problem with document.write
. If you are using it before the onload
event fires, as you presumably are, to build elements from structured data for instance, it is the appropriate tool to use. There is no performance advantage to using insertAdjacentHTML
or explicitly adding nodes to the DOM after it has been built. I just tested it three different ways with an old script I once used to schedule incoming modem calls for a 24/7 service on a bank of 4 modems.
By the time it is finished this script creates over 3000 DOM nodes, mostly table cells. On a 7 year old PC running Firefox on Vista, this little exercise takes less than 2 seconds using document.write
from a local 12kb source file and three 1px GIFs which are re-used about 2000 times. The page just pops into existence fully formed, ready to handle events.
Using insertAdjacentHTML
is not a direct substitute as the browser closes tags which the script requires remain open, and takes twice as long to ultimately create a mangled page. Writing all the pieces to a string and then passing it to insertAdjacentHTML
takes even longer, but at least you get the page as designed. Other options (like manually re-building the DOM one node at a time) are so ridiculous that I'm not even going there.
Sometimes document.write
is the thing to use. The fact that it is one of the oldest methods in JavaScript is not a point against it, but a point in its favor - it is highly optimized code which does exactly what it was intended to do and has been doing since its inception.
It's nice to know that there are alternative post-load methods available, but it must be understood that these are intended for a different purpose entirely; namely modifying the DOM after it has been created and memory allocated to it. It is inherently more resource-intensive to use these methods if your script is intended to write the HTML from which the browser creates the DOM in the first place.
Just write it and let the browser and interpreter do the work. That's what they are there for.
PS: I just tested using an onload
param in the body
tag and even at this point the document is still open
and document.write()
functions as intended. Also, there is no perceivable performance difference between the various methods in the latest version of Firefox. Of course there is a ton of caching probably going on somewhere in the hardware/software stack, but that's the point really - let the machine do the work. It may make a difference on a cheap smartphone though. Cheers!
You can combine insertAdjacentHTML method and document.currentScript property.
The insertAdjacentHTML()
method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position:
- 'beforebegin': Before the element itself.
- 'afterbegin': Just inside the element, before its first child.
- 'beforeend': Just inside the element, after its last child.
- 'afterend': After the element itself.
The Document.currentScript
property returns the <script>
element whose script is currently being processed. Best position will be beforebegin - new HTML will be inserted before <script>
itself.
<script>
document.currentScript.insertAdjacentHTML(
'beforebegin',
'this is the document.write alternative'
);
</script>
I'm not sure if this will work exactly, but I thought of
var docwrite = function(doc) {
document.write(doc);
};
This solved the problem with the error messages for me.
참고URL : https://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write
'developer tip' 카테고리의 다른 글
자식 푸시 후 로컬 실행 후크? (0) | 2020.11.27 |
---|---|
여러 목록에 포함 된 모든 값의 합집합을 만드는 Pythonic 방법 (0) | 2020.11.27 |
PHP stdObject에서 첫 번째 요소 가져 오기 (0) | 2020.11.26 |
Amazon EC2에서 시간대를 설정하는 방법은 무엇입니까? (0) | 2020.11.26 |
치명적인 오류 : 포착되지 않은 오류 : 정의되지 않은 함수 mysql_connect () 호출 (0) | 2020.11.26 |