Rdpi
Rdpi

Reputation: 581

Javascript best practices and document ready

I am developing a web application and during the development phases I am adding some scripts.

I noticed that the number of scripts are many and will probably increase.

I usually put everything enclosed in the document.ready and execute when the page is loaded.

There's a specific script that sets a specific style to an element ONLY if a class is present in the DOM.

Is there a way to run the script only if the specific element is in the DOM tree?

Upvotes: 3

Views: 418

Answers (3)

gen_Eric
gen_Eric

Reputation: 227220

You can load the script (via AJAX), or run the code when it's needed, by checking the length of the jQuery object to see if the element exists.

if($(selector).length > 0){ // if element is in DOM
    $.getScript('file.js'); // load file
    // or just run some code
    alert('element is here');
}

Or you can check out yepnope.js.

yepnope({
    test: $(selector).length,
    yep: 'file.js',
    callback: function(url, result, key){
      if(result){
        alert('element is here');
      }
    }
});

Upvotes: 4

Evan
Evan

Reputation: 6115

yeah I think you can do something like in ur document ready:

if ($('#yourElement').length){
     $.getScript('ajax/yourjs.js', function(){
         console.log('Load was performed.');
     });
}

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

To check for the existence of an element in jQuery, you can use $(#myElement").length;. To combine this with your question about adding CSS based on this, use:

if ($("#myelement").length > 0) {
    // element exists
    $(this).addClass("exists");
    $("#otherElement").css({
        "display": "block",
        "background-color": "#C00"
    });
}

Upvotes: 2

Related Questions