The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Load my .js code, only when ‘x’ DIV exists Re: Load my .js code, only when ‘x’ DIV exists



var script   = document.createElement("script");
script.type = "text/javascript";
script.src = "js/javascript.loading.js";

if ($("#example").length > 0){

Not sure if this is the best way of doing this, but it works.

Also check this out:
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("", 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