开发者

Awesome HTML minifying function but causes problem at Google Adsense ads - Very Important !

function works perfectly. it makes source code single line. but problem is about Google Adsense ads. their locations get messed up. what might be the reason ?

programming language is c# asp.net 4.0

here the function

    protected override void Render(HtmlTextWriter writer)
{
    if (this.Request.Headers["X-MicrosoftAjax"] != "Delta=tru开发者_开发问答e")
    {
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"<script[^>]*>[\w|\t|\r|\W]*?</script>");
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter sw = new System.IO.StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        base.Render(hw);
        string html = sb.ToString();
        System.Text.RegularExpressions.MatchCollection mymatch = reg.Matches(html);
        html = reg.Replace(html, string.Empty);
        reg = new System.Text.RegularExpressions.Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}|(?=[\r])\s{2,}");
        html = reg.Replace(html, string.Empty);
        reg = new System.Text.RegularExpressions.Regex(@"</body>");
        string str = string.Empty;
        foreach (System.Text.RegularExpressions.Match match in mymatch)
        {
            str += match.ToString();
        }
        html = reg.Replace(html, str + "</body>");
        writer.Write(html);
    }
    else
        base.Render(writer);
}


Maybe it messes up adsense locations because it moves all the <script> tags to the end of the body.


I think the problem might be that it makes the source a single line.

First, it could remove significant whitespace - spaces within block elements are significant but collapsable, so while you can replace them all with a single whitespace character, you can't remove them.

Secondly, sometimes insignificant whitespace is treated as significant due to browser bugs (though these are much fewer than they used to be).

Even without the second case, the first suffices that there's no good reason to expect the code to still work correctly after as extreme a reduction as you have here.

Finally, there's not much point in it anyway. Even with a large file it won't have much effect on render time, so it's only really going to improve download time, but since most whitespace in source is quite amenable to the deflate algorithm, it's going to be of little effect after you gzip or deflate it for transmission anyway (assuming you are using content-encoding to compress; if not, why waste time mangling source when you'll get much better tried-and-tested improvements with that?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜