Fawzan
Fawzan

Reputation: 4849

Tweak the load event on chrome extension

I have created a google chrome extension to replace certain images from third party websites. I have implement all the programming part but one of my requirements states that

On a slower net connection the original images should not be visible until it’s replaced by the new images

I am not sure wether it is achievable or not. I want to know what sort of event I should attach here. Can experts give their input on this?

This is the work I have done.

// get current websites base url
var current_website = window.location.href;

//run the code on specific pages
if ($.inArray(current_website, config.target_websites) != -1) {

    config.image_config.forEach(function (obj) {


        var src = obj.src;
        var target = obj.target;

        /**find all the occurances in the <img> tag */
        var key = 'img[src*="' + src + '"]';
        var img = $(key);

        /**replace it with the target image*/
        img.attr('src', target);


        /** check the inline CSS*/
        $("[style*=background-image]").css('background-image', function (i, oldimg) {
            return oldimg.indexOf(src) == -1 ? oldimg : 'url(' + target + ')';
        });

        /***check all the external styles for the image*/
        $('*').each(function () {
            if ($(this).css('background-image').indexOf(src) != -1) {
                $(this).css('background-image', 'url(' + target + ')');
            }
        });


    });



}

Upvotes: 0

Views: 109

Answers (1)

bazeblackwood
bazeblackwood

Reputation: 1204

Since you're already using jQuery, if you're not opposed to a small library (7.25 KB), you can use the jQuery plugin imagesloaded.

Basic usage:

// options
$('#container').imagesLoaded( {
  // options...
  },
  function() {
    // your code to run after load
  }
);

Then you could do a simple $('img').hide() on load, and $('img').show() after all images have loaded on your particular images.

You can see in the demo that it works for images which have been inserted dynamically into the page as well, which would meet your requirement for that the images of your key be hidden until replaced.

http://imagesloaded.desandro.com/

Upvotes: 1

Related Questions