Catching an HTTP event with JQuery

I have this JQuery code, but I need to know how to actually get the url from the selected tags.

$("link, script, style, a, img").each(function () {
    $(this).load(function () {
        // get the URL and log it
        console.log("Intercepted HTTP Event");


First of all, I need to do this in order to get the actual url at boot time.

The next thing I might need is to actually catch before the load event occurs, I mean, for example, before the image or link is loaded. Also, I need to change the url of the event to be executed, for example img

tag has src="/somewhere/image.png"

I mean this will trigger GET /somewhere/image.png

, I may need to change it toGET/otherplace/image.png

Any ideas how to achieve any of these?


source to share

3 answers

.attr ('src')




will fire after the content of the element has loaded. So you can get the url by executing $(this).attr("src")

or $(this).attr("href")

, but it's too late to stop the HTTP requests from exiting.

AFAIK, with modern browsers, there is no way for JavaScript to prevent the assets from loading in the first place. At best, you can change the images and stylesheets after the page has loaded by changing the attributes src

. If you do, make sure $(this).load()

not to go into an infinite loop. ( <a>

links are not a problem. Nothing loaded, so just change the attribute href




One way to solve this problem is to have some dummy links / hidden controls sourced from your external resource, and once the page is loaded, you will go through all such controls and then create the appropriate html elements, update the src attribute and then add it to dom.

Dummy controls:

<input type="hidden" source="/my/source/a.jpg" nodeType="img" class="specialControls"/>
<input type="hidden" source="/my/source/1.js" nodeType="script" class="specialControls" />


and javascript


        var elementType=$(this).attr("nodeType");
        $('<'+elementType+'/>').attr('src', $(this).attr("source"))




Hope it helps.



All Articles