theRatWonder
04-26-2007, 12:28 PM
I have heard that it is best practice to completely seperate the javascript from the markup, including all "onclick" attributes and the like. So:
<html>
<body>
<span onclick="alert('hello world!')">click</span>
</body>
</html>
is wrong, instead you should use something like:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('myspan').onclick = function() {alert('hello world!')};
}
</script>
</head>
<body>
<span id="myspan">click</span>
</body>
</html>
(except that ideally the javascript would be in an external file).
This poses a problem, that the "onclick" attribute doesn't get added to the element until the page loads, so if the page takes a long time to load fully, but most of it loads quite quickly, then someone might click on the element that should have the "onclick" attribute before it's actually been attached, and so nothing would happen.
Does anyone know of a principally sound way around this problem?
<html>
<body>
<span onclick="alert('hello world!')">click</span>
</body>
</html>
is wrong, instead you should use something like:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('myspan').onclick = function() {alert('hello world!')};
}
</script>
</head>
<body>
<span id="myspan">click</span>
</body>
</html>
(except that ideally the javascript would be in an external file).
This poses a problem, that the "onclick" attribute doesn't get added to the element until the page loads, so if the page takes a long time to load fully, but most of it loads quite quickly, then someone might click on the element that should have the "onclick" attribute before it's actually been attached, and so nothing would happen.
Does anyone know of a principally sound way around this problem?