I\'m getting the following error
Uncaught TypeError: Cannot read property \'appendChild\' of null
myRequest.onreadystatechange @ script.js
put your javascript at the bottom of the page (ie after the element getting defined..)
You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.
component.ts:
ngOnInit() {
this.loadScripts();
}
loadScripts() {
const dynamicScripts = [
//scripts to be loaded
"assets/lib/js/hand-1.3.8.js",
"assets/lib/js/modernizr.jr.js",
"assets/lib/js/jquery-2.2.3.js",
"assets/lib/js/jquery-migrate-1.4.1.js",
"assets/js/jr.utils.js"
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementById('scripts').appendChild(node);
}
}
component.html:
<div id="scripts">
</div>
You can also load styles similarly.
component.ts:
ngOnInit() {
this.loadStyles();
}
loadStyles() {
const dynamicStyles = [
//styles to be loaded
"assets/lib/css/ui.css",
"assets/lib/css/material-theme.css",
"assets/lib/css/custom-style.css"
];
for (let i = 0; i < dynamicStyles.length; i++) {
const node = document.createElement('link');
node.href = dynamicStyles[i];
node.rel = 'stylesheet';
document.getElementById('styles').appendChild(node);
}
}
component.html:
<div id="styles">
</div>
For people who have the same issue of querySelector
or getElementById
that returns the following error:
Uncaught TypeError: Cannot read property 'appendChild' of null
but you have a class name or id in the HTML...
If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer
to your script like so:
<script src="script.js" defer></script>
those getting querySelector or getElementById that returns the following error:
Uncaught TypeError: Cannot read property 'appendChild' of null
or any other property, even if you have a class name or id in the HTML
don't use (defer as it is too much browser dependent.)
<script src="script.js" defer></script> //don't use this
instead, put all your code in 'script.js' inside
$(document).ready(function(){
//your script here.
}