I've been focusing on my PHP skills lately but have been shifting to JavaScript. I'm familiar with the bare-bone basics of jQuery. I'm not as familiar with JavaScript as I'd like to be. I'm a solo-developer so I'd just like somebody to take a look at this and point out any mistakes or things I could be doing better.
What the code does
Creates an arbitrary number of <script>
elements, assigns a type
and src
attribute to each one and then inserts that <script>
element before the </body>
.
The code
See Better Code below!
function async_init() {
var element, type, src;
var parent = document.getElementsByTagName('body');
var cdn = new Array;
cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js';
cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js';
for (var i in cdn) {
element = document.createElement('script');
type = document.createAttribute('type');
src = document.createAttribute('src');
type.nodeValue = 'text/javascript';
src.nodeValue = cdn[i];
element.setAttributeNode(type);
element.setAttributeNode(src);
document.body.insertBefore(element, parent);
}
}
<body onload="async_init()">
Right now the code is working, which is great. But my questions:
- Is this the "best" way to do this? I define best as optimum user experience and efficient code.
- Are there any obvious "noobie" flaws in my JavaScript?
- Is there anyway I could get the
onload
attribute out of thebody
?
I used Mozilla Developer Network as my JavaScript reference. If there are any other references that are accurate, documented & useful I would love to have more information.
Thanks for checking the code out and your feedback, even if its pointing out how my code sucks!
Better code after critique
function async_init() {
var element;
var cdn = new Array;
cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js';
cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js';
for (var i in cdn) {
element = document.createElement('script');
element.setAttribute('type', 'text/javascript');
element.setAttribute('src', cdn[i]);
document.body.appendChild(element);
}
}
setAttribute
directly onelement
rather than creating explicit attribute nodes. It'd make the code ever so much less bulky. – Kerrek SB Jul 3 '11 at 23:26onload
, please. Always useaddEventListener
-- though you can only call that once the DOM has been created, so slingshoot it through an initialization function. – Kerrek SB Jul 3 '11 at 23:37onload
attribute via the body. It's actually far more stable thanaddEventListener
, which falls flat in IE < 8. – null Jul 4 '11 at 0:07