Search code examples
jqueryimageload

Jquery how to stop auto load imges when parseHTML


I have a page using Jquery $.ajax to get another page's html code. Here's what it looks like:

    <html><head>
    <script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script language="JavaScript" type="text/javascript">
    <!--
$(function(){
        $.ajax({
            url:another_page_url,
            async:false,
            dataType:"text",
            success:function(doc){ 
                //do something with $(doc) 
                //e.g. alert($(doc).find('img').attr('src'));}
        });
});
    //-->
    </script>
    </head>
    <body>
        <pre id="result" style="word-wrap: break-word; white-space: pre-wrap;"></pre>
    </body></html>

The another_page_url is a web page with lots of images like this:

<img src="http://ww3.sinaimg.cn/mw600/50cdeb22jw1e2a35t0w8ag.gif">

The problem is when I call $(doc) (equal to $.parseHTML(doc)) after success load, Jquery start ajax get requests to load all the images included in doc. My question is how to prevent this auto loading thing? I just want the image url string instead of these real images.

P.S. If I set dataType="xml" there will be a prase error.(Seems the page I want to load is not xml-compatible and I can't change it.) Set dataType="html" is equal to call $(doc) which lead me to the same situation.

Thanks for your help.


Solution

  • Thanks for everyone. I got my question resolved like this:

    $.ajax({
        url:url,
        async:false,
        dataType:"text",
        success:function(doc){ 
            var new_doc = doc.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {return "<img no_load_src=\"" +capture+ "\" />";});
            parse_function(new_doc);
        },
        error:function(jqXHR, textStatus, errorThrown){ alert(textStatus); }
    });
    

    Just two steps to solve this:

    • Explicitly set dataType="text" in $.ajax call so jquery won't detect and parse the return html document.
    • Use regex to replace all the img tag's src attribute before use it.(I change the <img attribute src="somewhere" /> to <img no_load_src="somewhere" /> to prevent jquery from load the real image.)