I got the same problem today.
Your answer pointed me in the right direction, because I had the EXACT same setup for script loading.
I had all my script tags on the top of the page (head) in the following order.
- JQuery
- SignalR
- /signalr/hubs
- my-script.js
And of course, the @Layout.cshtml was so thoughtful to add @Scripts.Render("~/bundles/jquery")
at the bottom of the <body>
tag.
Here's what's happening.
In this configuration, when the page loads, it loads up all the scripts in the head tag, in the order they're specified.
so it loads JQuery, then SignalR, which setup $.connection
then the auto-generated hubs script which sets up the $.connection.hubName
,then the site's custom script.
At this point your custom code runs. BUT your code at some point, waits for the body.onload
or document.onReady
before accessing the $.connection
By the time this event fires, the script bundle which the Layout template added for you at the end of body tag also downloads and executes. This bundle has the jquery library again.... which resets everything SignalR setup on $
and now your $.connection
is not defined anymore.
How to Solve It
Easy fix, make sure you don't load JQuery twice, once before SignalR and once after SignalR. I moved all my scripts to load after the bundle and it fixed the issue. Best practice here is to use the 'scripts' section provided by the template.
@section scripts{
@*/* load your scripts here. You can exclude jQuery,
coz it's already in the template */ *@
}
So this is not a SignalR error at all...
That's 2 hours of my life... I'll never get back ...
Hope This Helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…