Suppose I have a page such as the following
<html><head></head><body><!--STUFF-->
<script>
if(SomeBooleanVariable) {
$.getScript('js/file.js');
}
</script>
</body></html>
and my file.js file simply contains raw jQuery events with no wrapping. It is exactly as follows:
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
This is simply not working. When I include the contents of file.js directly into the HTML it works fine however the JS does not seem to be included properly. I have tried putting “alert(3);” at the top of file.js but it does not fire. I have tried the following:
$("head").append("<script src=\"js/file.js\" />");
$(document).append("<script src=\"js/file.js\" />");
-and-
document.write("<script src=\"js/file.js\" />");
If you want to load that .js file dynamically, change your code to this:
And see if you get any error in console
It may be, that you are, for example, using mod_rewrite and jQuery tries to load script relative to the “folder” your subpage is in. Example: you are @ http://www.example.com/link-to-subpage/. In this case, jQuery will try to load http://www.example.com/link-to-subpage/js/file.js, while it resides @ http://www.example.com/js/file.js. In this case, use an absolute path. So, instead of:
write: