2015-01-08 10 views
8

Perché si verifica un errore nel browser?TipoErrore: document.body è null

TypeError: document.body is null

codice sta lavorando bene in JSfiddle.

HTML

<head> 
    <meta charset="UTF-8"> 
    <title></title> 
    <script src="jsscript.js"></script> 
</head> 
<body> 
</body> 

JS

var creElem = document.createElement("p"); 
creElem.innerHTML = "Hellow World"; 
creElem.setAttribute("id", "id_name"); 
document.body.appendChild(creElem); 
+1

JSFiddle eseguire lo script dopo che la pagina caricata. ("onLoad" nel pannello di sinistra) – iForests

risposta

10

eseguire il codice quando viene caricata DOM. Racchiudi la tua logica in un listener di eventi per DOMContentLoaded.

document.addEventListener('DOMContentLoaded', function() { 
    // ... 
}); 

Il motivo per cui ha lavorato in JSFiddle è perché il JS viene eseguito su di carico (che è l'opzione predefinita in JSFiddle).


In alternativa, a seconda di quando si ha bisogno la logica da eseguire, si potrebbe anche usare:

window.addEventListener('load', function() { 
    // ... 
}); 

See: Difference between DOMContentLoaded and Load events