Dev Tip: loading JavaScript from JavaScript
A little dev tip for any of our Front End developer friends
The problem
Recently I was developing an interactive site for a client and it was intended to be a single page solution more like an app than a site, in that when a user clicked on a menu item the new content would be seamlessly loaded via asynchronous calls to avoid full page reloads.
It’s good practice to separate the code that provides the interaction control from the mark up so I had the JavaScript code in a separate file. But the content had interactive elements and these weren’t working.
The reason
When content is loaded the DOM (the mark up) has to finish loading before you can attach JavaScript event handlers to the elements. So in my scenario the code to handle the interactions had been loaded prior to the new content because even though I linked to the code at the end of the mark up it was parsed then executed which included loading the main content meaning that when the code was parsed the elements associated with them didn’t exist so when I subsequently clicked on them the click event wasn’t being captured.
What to do?
So now you have to separate the code associated with that section of content into a separate file and load that after the new content is loaded. OK we can do this but how best to link it?
One solution
You could add script tags in the HTML in the newly loaded content and it’ll work but it’s not the neatest way.
A worse solution
You could embed the script right there in the mark up – very messy.
The neat way
jQuery has a really cool one-liner to deal with this and as I’m using jQuery already to make life easy then it’s a super cool way of getting my new interaction code loaded at the right time whilst keeping the business logic separate from the display mark up.
Simply add the following line of code immediately after the call to load,
$.getScript("./path/to/my/lovely/script.js");
And if you name your script file the same as the content files then you can have simple function to handle loading content and associated business logic that looks like this:
function loadContent(theSection){
var filename;
switch(theSection.toLowerCase()){
case "products":
filename = "products";
break;
case "services":
filename = "services";
break;
case "about us":
filename = "about-us";
break;
case "contact us":
filename = "contact-us";
break;
case "the gallery":
filename = "gallery";
break;
default:
filename = "home";
break;
}
$('#content_outer').load("./"+filename+".inc");
$.getScript("./_res/script/"+filename+".js");
}//loadContent
I hope this is helpful to you. Do have any other or neater ways of achieving the same results – if so please share in the comments below. Have a great day.