I appreciate that this will heavily depend on requirements, but I'm fairly new to attaching events to elements externally.
I wanted to know of the best practice to identify page specific scripts and events and minimising the JS in the HTML templates. Here is my first attempt:
- Add a global variable for the page
- In external script detect that variable and set up events based on it
Inline JS:
<script>
var gc_pageType = 'report';
</script>
External JS:
// report functions
function reportFunctions() {
lo_element = document.getElementById('firstname');
addEventHandler(lo_element, 'blur', alertOnBlur);
}
function alertOnBlur() {
alert('worked');
}
// general functions
function pageScripts() {
switch(gc_pageType) {
case 'report':
reportFunctions();
}
}
if(window.addEventListener){
window.addEventListener('load',pageScripts,false); //W3C
}
else{
window.attachEvent('onload',pageScripts); //IE
}
function addEventHandler(elem,eventType,handler) {
if (elem.addEventListener) {
elem.addEventListener (eventType,handler,false);
}
else if (elem.attachEvent) {
elem.attachEvent ('on'+eventType,handler);
}
}
Is it more efficient to just split out into separate files even when the content is so minimal, or add onload tags to the body tag? Any input would be appreciated!
Any input would be great.