DEV Community

Cameron Wardzala
Cameron Wardzala

Posted on • Originally published at dangerisgo.com on

1 1

Using SignalR with RequireJS

If you don’t know about SignalR and RequireJS

When I was building my app with SignalR and RequireJS there were two steps I needed before stuff would work.

1. Setup dependencies

I needed to wrap all my SignalR javascript so they will work properly with RequireJS.

require.config({
    paths: {
        jquery: 'jquery-1.8.2.min'
    },
    shim : {
        "jquery.signalR-0.5.3": ['jquery'],
        "/signalr2/hubs": ['jquery', 'jquery.signalR-0.5.3'],
    }
});
Enter fullscreen mode Exit fullscreen mode

Using the great shim feature of RequireJS 2. I can use non-AMD compatible scripts with RequireJS without manually wrapping them in define() statements. I also set the path for jquery because it is a named module and is required by the SignalR scripts.

2. Fix SignalR $.connection.hub.start()

I am calling SignalR’s $.connection.hub.start() from within a $(document).ready(). Even before I started using RequireJS to load my scripts this worked fine. However, after moving to RequireJS this stopped working. Why? basically, SignalR will by default delay starting your connection until the page has completely loaded. Enter the waitForPageLoad option on $.connection.hub.start(). This tells SignalR if you want to wait for the page to load before starting your connection which in my case I don’t. Simply set that option to false and it will start the connection when invoked instead of waiting. This fixed my issues and SignalR and RequireJS started playing nice together. Note: I am also using a callback on start() to make sure my connection has been established before using my server methods.

$(document).ready(function () {
    $.connection.hub.start({waitForPageLoad:false},function () {
        // callback code
    });
});
Enter fullscreen mode Exit fullscreen mode

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

AWS Industries LIVE!

AWS Industries LIVE! features AWS Partners discussing various topics related to their industry, their solutions, and how they can help customers.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️