반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

두둥탁!

자바스크립트 Cannot read properties of null (reading 'appendChild') 본문

공부/오류

자바스크립트 Cannot read properties of null (reading 'appendChild')

두둥탁! 2022. 8. 2. 21:34
반응형

자바스크립트 appendChild 오류

자세히는 모르지만 대충 null의 프로퍼티를 읽을 수 없다는 뜻인 것 같다.

왜 읽을 수 없나 했더니..

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="app.js"></script>		<!-- 얘 때문임 -->
</head>
<body>
	~~생략~~
</body>

HTML을 파싱 하다가 <script> 태그가 보이면 파싱을 멈춘 뒤

스크립트를 다운로드 후 스크립트 파일 실행까지 하고 나서

나머지 HTML을 파싱 하는데 <body> 태그를 파싱하기도 전에 스크립트를 실행해버려서 위와 같은 오류가 발생한 것이었다.


이 오류를 해결하기 위한 2가지 방법이 있는데

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
<body>
	~~생략~~
    <script src="app.js"></script>
</body>

<body> 태그의 맨 밑에 놓는 방법과(↑↑↑↑)

<head> 태그에 놓고 <script> 태그의 속성에 defer을 쓰는 방법이 있다.(↓↓↓↓)

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script defer src="app.js"></script>
</head>
<body>
	~~생략~~
</body>

✅첫 번째 방법

HTML 파싱 → HTML 파싱 완료 → 스크립트 파일 다운로드 → 스크립트 파일 실행 순으로 진행

 

✅두 번째 방법

HTML 파싱하다가 <script> 태그의 defer 발견 시 스크립트 파일 다운로드 동시 진행 → HTML 파싱 완료 → 스크립트 파일 실행 순으로 진행

 

두 번째 방법이 조금 더 효율적인 것 같다는 생각이 든다.

반응형