Skip to content Skip to sidebar Skip to footer

When Jquery Parsing Html - Chrome Throwing Net::err_file_not_found

Here is my code: In Chrome I'm getting error: GET file:///C:/Users/mstefanow/Desktop/images/relative/path.jpg net::ERR_FILE_NOT_FOUND (it doesn't throw this error in IE Edge, IE

Solution 1:

Now as I understand what's going on I can provide an answer

http://api.jquery.com/jQuery/#jQuery2

if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML

Here: jQuery parse html without loading images

html = html.replace(/<img[^>]*>/g,"");

(some clever regexp to remove image tags)

It looks like an uphill battle - I'd have to:

  • find images by regexp
  • know which are the right ones
  • extract attributes

All that without using convenience parse methods.


Still not sure why error appears only in Chrome - see my comment: When jQuery parsing html - Chrome throwing net::ERR_FILE_NOT_FOUND

Solution 2:

Why this is happening

When using $.parseHTML, all your HTML is parsed in DOMNodes with your document.

So <img src="animage.png"/> result as

var img = document.createElement("img");
img.src = "animage.png"; // start loading image

How to avoid this

You can't prevent for showing an error in the console when loading image.

As stated in your post, all relative paths for images can't work so your only solution is to replace these relative paths with an empty image.

var htmlString = '<img class="aclass" src="images/relative/path.jpg" anattribute/>\
<img src="/animage">\
<img class="aclass" src="images/relative/path.jpg" anattribute/>';

htmlString = htmlString.replace(/(img[^>]+src=(?:"|'))([^\/][^'"]+)/g, "$1//:0");
$.parseHTML(htmlString);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

I'm not a Regex expert, I guess it could be improved.

Solution 3:

You can simplify you question to "Can I suppress an 404 error when an image source is broken?"

The answer is NO, you can attach a handler <img src='...' onerror='' /> but it will always be called after the 404 error and there is no way to avoid that.

That's exactly what the .parseHTML is doing, in your case it calls jQuery.buildFragment which will create the elements tree from the given string. It uses innerHTML for loading the elements into the default or custom context.

The only way to achieve your goal is to detect images before you parse the string, trying to load them with a request to a server side script which will handle the attempt and return the image or a default one.

Post a Comment for "When Jquery Parsing Html - Chrome Throwing Net::err_file_not_found"