Home › Forums › JavaScript › Load my .js code, only when ‘x’ DIV exists › Re: Load my .js code, only when ‘x’ DIV exists
June 21, 2012 at 2:36 pm
#104721
Participant
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/javascript.loading.js";
if ($("#example").length > 0){
document.head.appendChild(script);
}
Demo: http://jsfiddle.net/john_motyl/McNTG/
Not sure if this is the best way of doing this, but it works.
Also check this out: http://api.jquery.com/jQuery.getScript/
Seems like this could be a more semantic approach to dynamically using js files. I hope this helped.
This works as well and is pretty cool:
$(function() {
if ( $('div').length > 0 )
{
$.getScript("http://malsup.github.com/jquery.easing.1.3.js", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
})
.fail(function(jqxhr, settings, exception) {
$( "div" ).text( "ajax request for script failed." );
});
}
});
I feel that the .fail()
is acting like a try