Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery ready() function but still not fast enough? Ideas?

Small question that I hope someone can answer.

I'm creating this personal chrome extension to help me test out content manipulation on various sites. On one of these sites, I am simply replacing an existing <img> with a different image and wrapping that jquery replaceWith() function in $(document).ready() function.

When navigating to the page, though, you can still see the original image for a split second before it swaps them.

Is there any way to arrest the loading page until the image swap completes?

like image 766
Chaz Avatar asked Apr 20 '11 18:04

Chaz


People also ask

What is the purpose of the following jQuery ready () call?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Can I use jQuery without document ready?

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Can there be more than one ready function in jQuery?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

What is $( document .ready () and $( window .load () in jQuery which one will be fired first?

ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.


2 Answers

Presumably, the <img> element is uniquely identifiable in some way (such as it's src attribute or an id). If that's the case, quickly add a stylesheet when the document is created, this stylesheet should target the <img> element and hide it from site. Then, during your .ready() handler, disable/remove the stylesheet.

var ss = document.createElement("style");
ss.textContent = "img[src='/path/to/img.png'] { visibility: hidden; }";
document.documentElement.childNodes[0].appendChild(ss);

$(document).ready(function () { 
    ss.parentNode.removeChild(ss);

    // swap image here
});
like image 196
Andy E Avatar answered Oct 03 '22 11:10

Andy E


no. any attempt to do that will result in the page not being "ready" which will result in you not reaching a state where you can swap the image out.

like image 21
FatherStorm Avatar answered Oct 03 '22 10:10

FatherStorm