Skip to content

Instantly share code, notes, and snippets.

@vitaliel
Created October 27, 2021 14:46
Show Gist options
  • Save vitaliel/dff3170c327e6d1e80ae294994c03dd2 to your computer and use it in GitHub Desktop.
Save vitaliel/dff3170c327e6d1e80ae294994c03dd2 to your computer and use it in GitHub Desktop.
POC for replacing inline images with separate http requests
using System;
using System.Linq;
using AngleSharp.Html.Parser;
namespace ParsingCheck
{
public class AngleCheck
{
// POC for replacing inline images with separate http requests
// AngleSharp v0.16.1
public static void Parse(string html)
{
var parser = new HtmlParser();
var doc = parser.ParseDocument(html);
var imgs = doc.QuerySelectorAll("img")
.Where(x => x.HasAttribute("src") && x.GetAttribute("src")!.StartsWith("data:"));
var i = 1;
// x.HasAttribute("src")
// x.Attributes["src"].Value
foreach (var img in imgs)
{
Console.WriteLine($"src: {img.GetAttribute("src")}");
img.SetAttribute("src", $"/api/{i}");
img.SetAttribute("loading", "lazy");
i++;
}
Console.WriteLine("== Result html");
// avoid html,body tags for fragments
Console.WriteLine(doc.QuerySelector("body")?.InnerHtml);
}
}
}
<p>
<img src="x1">
</p>
<p>
<img src="data:x1">
</p>
<div>
<img data-src="data:x1">
</div>
<p>This is from stage server:</p><p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAQQCAIAAACMTtFPAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAP+HSURBVHhe7L0JlF3VdebvtboTp51enX">
src: data:x1
src: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAQQCAIAAACMTtFPAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAP+H
SURBVHhe7L0JlF3VdebvtboTp51enX
== Result html
<p>
<img src="x1">
</p>
<p>
<img src="/api/1" loading="lazy">
</p>
<div>
<img data-src="data:x1">
</div>
<p>This is from stage server:</p><p><img src="/api/2" loading="lazy">
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment