You need to execute any specific jQuery code only after loading the script, which, obviously, can happen at a much later point in time after adding it to the section of the chapter:
function include(filename, onload) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; script.onload = script.onreadystatechange = function() { if (script.readyState) { if (script.readyState === 'complete' || script.readyState === 'loaded') { script.onreadystatechange = null; onload(); } } else { onload(); } }; head.appendChild(script); } include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() { $(document).ready(function() { alert('the DOM is ready'); }); });
And here is a live demonstration .
You can also see script loaders, such as yepnope or RequireJS , which make this task easier.
source share