Blog

Tagged by 'disqus'

  • Disqus is a popular commenting system used on many websites and seems to be the go-to for bloggers who want to add some form of engagement from their readers. I’ve used Disqus ever since I had a blog and never experienced any problems even throughout the different iterations this site has gone through over the years.

    No complaints here, for a free service that encompasses both function and form.

    Even since I redeveloped my site in July, I’ve attempted to make page performance of paramount importance and put pages on a strict diet by removing unnecessary third-party plugins. Even though I was fully aware that Disqus adds bloat, I just assumed it's a necessary evil. However, I felt I really had to do something after reading a blog post by Victor Zhou on the reasons why he decided to move away from Disqus. The reasons are pretty damning.

    Disqus increases both the page load requests and weight. I can confirm these findings myself. On average, Disqus was adding around 1.6MB-2MB of additional bloat to my blog pages. This is the case even when a blog post had no comments. As a result, the following Google Lighthouse scores took a little beating:

    • Performance: 82/100
    • Best Practices: 75/100

    Pretty bad when you take into consideration that most of the pages on my site consist of text and nothing overly complex.

    Migrating to another commenting provider as Victor Zhou had done could be an option. There are other options I've noticed my fellow bloggers use, such as:

    Each one of these options has its pros and cons whether that might be from a pricing or feature standpoint. I decided to remain with Disqus for the moment as migrating comments is another task I don't currently have time to perform. I would be content in keeping Disqus if I could find a way to negate the page bloat by lazy-loading Disqus on demand.

    I've seen other Disqus users going down the lazy-loading approach within their builds, but couldn't find anything specifically for a Gatsby JS site. Luckily, the solution is quite straightforward and requires minimal code changes.

    Code

    The GatsbyJS gatsby-plugin-disqus plugin makes it easy to integrate Disqus functionality. All that needs to be done is to add the following component to the page:

    ...
    ...
    let disqusConfig = {
            url: `${site.siteMetadata.siteUrl+postUrl}`,
            identifier: postId,
            title: postTitle,
        }
    ...
    ...
    ...
    <Disqus config={disqusConfig} />
    ...
    ...
    

    The only way to add lazyload functionality to this plugin is by controlling when it should be rendered. I decided to render Disqus through a simple button click.

    import { useStaticQuery, graphql } from "gatsby";
    import React, { useState } from 'react';
    import { Disqus } from 'gatsby-plugin-disqus';
    
    const DisqusComponent = ({ postId, postTitle, postUrl }) => {
        const [disqusIsVisible, setDisqusVisibility] = useState(false);
    
        // Set Disqus visibility state on click.
        const showCommentsClick = event => {
          setDisqusVisibility(true);
        };
    
        let disqusConfig = {
            url: postUrl,
            identifier: postId,
            title: postTitle,
        }
    
        return (
          <>
            {!disqusIsVisible && (
              <div>
                <button onClick={showCommentsClick}>Load Comments</button>
              </div>
            )}
            {disqusIsVisible && (
              <Disqus config={disqusConfig} />
            )}
          </>
        )
    }
    

    The code above is an excerpt from a React component I place within a blog post page. React state is used to set the visibility via the showCommentsClick() onClick function. When this event is fired, two things happen:

    1. The "Load Comments" button disappears.
    2. Disqus comments are rendered.

    We can confirm the lazyloading capability works by looking at the "Network" tab in Chrome Developer Tools. You probably won't notice the page speed improvement in delaying the load of Disqus, but within the "Network" tab you'll see a lower number of requests.

    Disqus Lazy-Loading Demo

    Conclusion

    Changing the way Disqus loads on a webpage may come across as a little pedantic and an insignificant performance improvement. I believe where performance savings can be made, it should be done. Since I have rolled out the Disqus update across all pages based on the approach discussed here, the Google Lighthouse scores have increased to:

    • Performance: 95/100
    • Best Practices: 92/100

    For the first time, my website has a Google Lighthouse score ranging between 95-100 across all testing criteria.

    Conclusion - Part 2

    As I neared the end of writing this post, I just happened to come across another Gatsby Disqus plugin - disqus-react, that another blogger Janosh wrote about. This is the officially supported React plugin written by the Disqus team and contains lazy-load functionality:

    All Disqus components are lazy-loaded, meaning they won’t negatively impact the load times of your posts (unless someone is specifically following a link to one of the comments in which case it takes a little longer than on a purely static site).

    Could this really be true? Was this post written in vain?

    Janosh had stated he is using this plugin on his website and out of curiosity, I decided to download the disqus-react git repo and run the code examples locally to see how Disqus gets loaded onto the page.

    I ran both Google Lighthouse and checked Chrome's "Network" tab and after running numerous tests, no lazy-loading functionality was present. I could see Disqus JS files and avatar images being served on page load. I even bulked up the blog post body content to ensure Disqus was not anywhere in view - maybe the component will only load when in view? This made no difference.

    Unless anyone else can provide any further insight, I will be sticking to my current implementation.

  • Published on
    -
    3 min read

    BlogEngine Disqus Comment Count Fix

    For those of you that have decided to opt out of using BlogEngine’s default commenting system and instead, use Disqus platform will probably encounter a minor issue. The minor issue being the fact that the comment count displayed in within post view doesn’t actually work.

    I needed to make a few modifications to the way Disqus is used within BlogEngine. I have to say that I wasn’t exactly impressed with the way Disqus was setup within the JavaScript code (maybe over-exaggerating). You’ll see what I mean from the Disqus JavaScript code found in “post.aspx” and “page.aspx”:

    <script type="text/javascript">
        var disqus_url = '<%= Post.PermaLink %>';
        var disqus_developer = '<%= BlogEngine.Core.BlogSettings.Instance.DisqusDevMode ? 1 : 0 %>';
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = 'http://<%=BlogEngine.Core.BlogSettings.Instance.DisqusWebsiteName %>.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    

    I believe that additional Disqus variable’s should be used, such as:

    • disqus_title - Tells the Disqus service the title of the current page.
    • disqus_identifier -  If this variable is undefined, the page's URL will be used. The URL can be unreliable, such as when renaming an article slug or changing domains, so its recommended using your own unique way of identifying a thread.

    After you have made this change, your JavaScript should look like this:

    <script type="text/javascript">
        var disqus_title = '<%=Post.Title %>';
        var disqus_identifier = '<%= Post.Id.ToString() %>';
        var disqus_url = '<%= Post.AbsoluteLink %>';
        var disqus_developer = '<%= BlogEngine.Core.BlogSettings.Instance.DisqusDevMode ? 1 : 0 %>';
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = 'http://<%=BlogEngine.Core.BlogSettings.Instance.DisqusWebsiteName %>.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    

    You may or may not have noticed the “disqus_url” is getting assigned the Post.AbsoluteLink rather than Post.PermaLink. I prefer using the AbsoluteLink since it will output a nice clean friendly URL.

    The next thing we need to do is modify the “PostView.ascx” file found in your themes folder. The line we are looking for is where the Disqus comments link is set.

    <% if (BlogEngine.Core.BlogSettings.Instance.ModerationType == BlogEngine.Core.BlogSettings.Moderation.Disqus)
    { %>
        <a rel="nofollow" href="<%=Post.PermaLink %>#disqus_thread"><%=Resources.labels.comments %></a>
    <%}
        else
    { %>
        <a rel="bookmark" href="<%=Post.PermaLink %>" title="<%=Server.HtmlEncode(Post.Title) %>">Permalink</a> |
        <a rel="nofollow" href="<%=Post.RelativeLink %>#comment"><%=Resources.labels.comments %> (<%=Post.ApprovedComments.Count %>)</a>   
    <%} %>
    

    We need to make two changes to the current comments code. Firstly, we need to add an important missing attribute to the anchor tag. The missing tag is the “data-disqus-identifier”. This is recommended practice by the Disqus Developer guide. Secondly, we need to change the “href” attribute to use an AbsoluteLink instead of a PermaLink. The code should now look like this:

    <% if (BlogEngine.Core.BlogSettings.Instance.ModerationType == BlogEngine.Core.BlogSettings.Moderation.Disqus)
    { %>
        <a rel="nofollow" href="<%=Post.AbsoluteLink %>#disqus_thread" identifier="<%= Post.Id.ToString() %>"><%=Resources.labels.comments %></a>
    <%}
        else
    { %>
        <a rel="nofollow" href="<%=Post.RelativeLink %>#comment"><%=Resources.labels.comments %> (<%=Post.ApprovedComments.Count %>)</a>   
    <%} %>
    

    From personal experience, I believe it is best to carry out the “post.aspx” and “page.aspx” code changes before moving onto the Disqus platform. If you currently have comments that need to be exported to Disqus, I found this exporter tool really useful. Be prepared to carry out a few Disqus imports to get things exactly right.