Skip to content

Commit 61bc6bd

Browse files
authored
Script Loader updates + other docs update (#544)
* Script Loader component updates.
1 parent dc1edbd commit 61bc6bd

File tree

11 files changed

+143
-32
lines changed

11 files changed

+143
-32
lines changed

BlazorBootstrap.Demo.RCL/Pages/Grid/Grid_Demo_16_Save_And_Load_Grid_Settings.razor

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@
5454
{
5555
var settingsJson = await JS.InvokeAsync<string>("window.localStorage.getItem", "grid-settings");
5656
if (string.IsNullOrWhiteSpace(settingsJson))
57-
return null;
57+
return null!;
5858

5959
var settings = JsonSerializer.Deserialize<GridSettings>(settingsJson);
6060
if (settings is null)
61-
return null;
61+
return null!;
6262

6363
return settings;
6464
}

BlazorBootstrap.Demo.RCL/Pages/Index.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
<span class="px-1"></span>
2525
<a href="https://www.nuget.org/packages/Blazor.Bootstrap/"><img alt="Nuget" src="https://img.shields.io/nuget/dt/Blazor.Bootstrap"></a>
2626
</p>
27-
<CarbonAds ClassNames="d-flex justify-content-center" />
27+
<CarbonAds Class="d-flex justify-content-center mt-5" />
2828
</div>
2929
</div>
3030
</div>

BlazorBootstrap.Demo.RCL/Pages/Offcanvas/Offcanvas_Demo_04_Static_Backdrop.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<p>Vestibulum sed aliquam urna. Ut ullamcorper erat vitae velit mattis commodo. Phasellus dignissim rhoncus dapibus. Quisque congue egestas tellus id finibus. Suspendisse nibh felis, mattis et finibus vel, tempor in lectus. Nullam eget eros dui. Mauris eget vestibulum nibh. Nullam mattis malesuada lorem vel condimentum. Mauris id odio ac est feugiat condimentum.</p>
88
</BodyTemplate>
99
<FooterTemplate>
10-
<Button Color="ButtonColor.Secondary" @onclick="() => offcanvas?.HideAsync()">Close</Button>
10+
<Button Color="ButtonColor.Secondary" @onclick="() => offcanvas.HideAsync()">Close</Button>
1111
</FooterTemplate>
1212
</Offcanvas>
1313

BlazorBootstrap.Demo.RCL/Pages/ScriptLoader/ScriptLoaderDocumentation.razor

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111

1212
<CarbonAds />
1313

14-
<SectionHeading Size="HeadingSize.H2" Text="How it works" PageUrl="@pageUrl" HashTagName="how-it-works" />
14+
<SectionHeading Size="HeadingSize.H2" Text="How it works" PageUrl="@pageUrl" HashTagName="how-it-works" />
1515
<div class="mb-3">
16-
In the following example, the jQuery script is loaded using the Script Loader component.
16+
In the following example, the jQuery script is loaded using the Script Loader component.
1717
</div>
1818
<Demo Type="typeof(ScriptLoader_Demo_01_Examples)" />
1919

@@ -23,6 +23,34 @@
2323

2424
<img src="https://i.imgur.com/EWEGAZv.png" class="img-fluid" alt="Blazor Script Loader - Test whether the jQuery script has been loaded successfully" />
2525

26+
<SectionHeading Size="HeadingSize.H2" Text="Events" PageUrl="@pageUrl" HashTagName="events" />
27+
<div class="mb-3">
28+
Blazor Bootstrap Script Loader component exposes two events.
29+
<table class="table">
30+
<thead>
31+
<tr>
32+
<th scope="col">Event Name</th>
33+
<th scope="col">Description</th>
34+
</tr>
35+
</thead>
36+
<tbody class="table-group-divider">
37+
<tr>
38+
<th scope="row"><code>OnError</code></th>
39+
<td>An event that is fired when a script loading error occurs.</td>
40+
</tr>
41+
<tr>
42+
<th scope="row"><code>OnLoad</code></th>
43+
<td>An event that is fired when a script has been successfully loaded.</td>
44+
</tr>
45+
</tbody>
46+
</table>
47+
</div>
48+
<div>
49+
In the following example, an incorrect script source is specified.
50+
This is why the <code>OnError</code> callback event is called, and the message is updated with the error message.
51+
</div>
52+
<Demo Type="typeof(ScriptLoader_Demo_02_Events)" />
53+
2654
@code {
2755
private string pageUrl = "/script-loader";
2856
private string title = "Blazor ScriptLoader Component";
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<ScriptLoader Async="true"
2+
Class="mt-4"
3+
OnLoad="OnScriptLoad"
4+
OnError="OnScriptError"
5+
ScriptId="script2"
6+
Source="//cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min1.js"/>
7+
8+
<div class="text-danger">@message</div>
9+
10+
@code {
11+
string? message;
12+
private void OnScriptLoad() => message = "Script loaded successfully.";
13+
private void OnScriptError(string errorMessage) => message = errorMessage;
14+
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
@namespace BlazorBootstrap.Demo.RCL
22

33
<ScriptLoader Async="true"
4-
Class="@classNames"
4+
Class="@Class"
55
ScriptId="_carbonads_js"
66
Source="//cdn.carbonads.com/carbon.js?serve=CWYICKQU&placement=docsblazorbootstrapcom" />

BlazorBootstrap.Demo.RCL/Shared/Components/CarbonAds.razor.cs

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,10 @@
22

33
public partial class CarbonAds : ComponentBase
44
{
5-
#region Fields and Constants
6-
7-
private string? classNames;
8-
9-
#endregion
10-
115
#region Properties, Indexers
126

137
[Parameter]
14-
public string? ClassNames
15-
{
16-
get => classNames;
17-
set => classNames = $"mt-5 {value ?? ""}".Trim();
18-
}
8+
public string? Class { get; set; }
199

2010
#endregion
2111
}

blazorbootstrap/Components/ScriptLoader/ScriptLoader.razor.cs

Lines changed: 52 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,33 @@
11
namespace BlazorBootstrap;
22

3+
/// <summary>
4+
/// A component for loading scripts dynamically in a Blazor application.
5+
/// </summary>
36
public partial class ScriptLoader : BlazorBootstrapComponentBase
47
{
58
#region Fields and Constants
69

10+
/// <summary>
11+
/// The default content type for scripts.
12+
/// </summary>
713
private const string type = "text/javascript";
814

15+
/// <summary>
16+
/// A reference to this component instance for use in JavaScript calls.
17+
/// </summary>
18+
private DotNetObjectReference<ScriptLoader> objRef = default!;
19+
920
#endregion
1021

1122
#region Methods
1223

13-
protected override async Task OnAfterRenderAsync(bool firstRender)
24+
protected override async Task OnInitializedAsync()
1425
{
15-
if (firstRender)
16-
await JS.InvokeVoidAsync("window.blazorBootstrap.scriptLoader.load", ElementId, Async, ScriptId, Source, type);
26+
objRef ??= DotNetObjectReference.Create(this);
27+
28+
ExecuteAfterRender(async () => { await JS.InvokeVoidAsync("window.blazorBootstrap.scriptLoader.initialize", ElementId, Async, ScriptId, Source, type, objRef); });
1729

18-
await base.OnAfterRenderAsync(firstRender);
30+
await base.OnInitializedAsync();
1931
}
2032

2133
protected override void OnParametersSet()
@@ -26,6 +38,27 @@ protected override void OnParametersSet()
2638
base.OnParametersSet();
2739
}
2840

41+
/// <summary>
42+
/// Handles a script error event from JavaScript.
43+
/// </summary>
44+
/// <param name="errorMessage">The error message.</param>
45+
[JSInvokable]
46+
public void OnErrorJS(string errorMessage)
47+
{
48+
if (OnError.HasDelegate)
49+
OnError.InvokeAsync(errorMessage);
50+
}
51+
52+
/// <summary>
53+
/// Handles a script load event from JavaScript.
54+
/// </summary>
55+
[JSInvokable]
56+
public void OnLoadJS()
57+
{
58+
if (OnLoad.HasDelegate)
59+
OnLoad.InvokeAsync();
60+
}
61+
2962
#endregion
3063

3164
#region Properties, Indexers
@@ -34,20 +67,31 @@ protected override void OnParametersSet()
3467
protected override bool ShouldAutoGenerateId => true;
3568

3669
/// <summary>
37-
/// Gets or sets the async.
70+
/// Gets or sets a value indicating whether the script should be loaded asynchronously.
3871
/// </summary>
3972
[Parameter]
4073
public bool Async { get; set; }
4174

4275
/// <summary>
43-
/// Gets or set the script id.
76+
/// An event that is fired when a script loading error occurs.
77+
/// </summary>
78+
[Parameter]
79+
public EventCallback<string> OnError { get; set; }
80+
81+
/// <summary>
82+
/// An event that is fired when a script has been successfully loaded.
83+
/// </summary>
84+
[Parameter]
85+
public EventCallback OnLoad { get; set; }
86+
87+
/// <summary>
88+
/// Gets or sets the ID of the script element.
4489
/// </summary>
4590
[Parameter]
4691
public string? ScriptId { get; set; }
4792

4893
/// <summary>
49-
/// This parameter specifies the URI of an external script; this can be used as an alternative to embedding a script
50-
/// directly within a document.
94+
/// Specifies the URI of the external script to load.
5195
/// </summary>
5296
[Parameter]
5397
[EditorRequired]

blazorbootstrap/Components/Tabs/Tabs.razor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ private async Task ShowTabAsync(Tab tab)
211211
await JS.InvokeVoidAsync("window.blazorBootstrap.tabs.show", tab.ElementId);
212212

213213
if (tab?.OnClick.HasDelegate ?? false)
214-
await tab.OnClick.InvokeAsync(new TabEventArgs(tab.Name, tab.Title));
214+
await tab.OnClick.InvokeAsync(new TabEventArgs(tab!.Name, tab.Title));
215215
}
216216

217217
#endregion

blazorbootstrap/wwwroot/blazor.bootstrap.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -562,10 +562,10 @@ window.blazorBootstrap = {
562562
}
563563
},
564564
scriptLoader: {
565-
load: (elementId, async, scriptId, source, type) => {
565+
initialize: (elementId, async, scriptId, source, type, dotNetHelper) => {
566566
let scriptLoaderEl = document.getElementById(elementId);
567567

568-
if (source.length == 0) {
568+
if (source.length === 0) {
569569
console.error(`Invalid src url.`);
570570
return;
571571
}
@@ -583,9 +583,13 @@ window.blazorBootstrap = {
583583
if (type != null)
584584
scriptEl.type = type;
585585

586-
scriptEl.onerror = function () {
587-
console.error(`An error occurred while loading the script: ${source}`);
588-
}
586+
scriptEl.addEventListener("error", (event) => {
587+
dotNetHelper.invokeMethodAsync('OnErrorJS', `An error occurred while loading the script: ${source}`);
588+
});
589+
590+
scriptEl.addEventListener("load", (event) => {
591+
dotNetHelper.invokeMethodAsync('OnLoadJS');
592+
});
589593

590594
if (scriptLoaderEl != null)
591595
scriptLoaderEl.appendChild(scriptEl);

0 commit comments

Comments
 (0)