mitch
mitch

Reputation: 2245

JQuery, load elements after page loaded

I want to do something like this:

<img src="" class="after-all" data="/assets/huge-bg.png" />
<div class="after-all" data="/actions/div-content.html"></div>

And in JS

$("after-all").loadMissing();

I think the best way is build a plugin with recognize method:

if (img) $(this).attr('src', $(this).attr('data'));
if (div) $(this).load($(this).attr('data'));

Is this possible ? What is the best way to do this ? How to do this ?

Upvotes: 1

Views: 340

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263137

You can use is():

$.fn.loadMissing = function() {
    return this.each(function() {
        var $this = $(this);
        if ($this.is("img")) {
            $this.attr("src", $this.attr("data"));
        } else if ($this.is("div")) {
            $this.load($this.attr("data"));
        }
    });
};

Note that you should use another attribute than data to store this information. An HTML5 data attribute like data-content might be a better solution.

Upvotes: 1

Related Questions