What's the best way to dynamically insert CSS files into my TMS WEB Core website using Delphi?
I want to load a certain CSS file depending on the theme (dark/light). So whenever the website opens, then it needs to dynamically load the correct CSS file.
How can this be achieved?
The TApplication
class has an InsertCSS
and RemoveCSS
function that can be used for this.
So as an example, let's say I want to dynamically load Bootstrap into my application with a button click, I could do this:
procedure TfrmMain.WebButton1Click(Sender: TObject);
begin
Application.InsertCSS('MyCSS', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css');
end;
You could also do this directly in the .dpr
file such as:
program TestApp;
{$R *.dres}
uses
Vcl.Forms,
WEBLib.Forms,
uIndex in 'uIndex.pas' {frmMain: TWebForm} {*.html};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TfrmMain, frmMain);
Application.InsertCSS('MyCSS', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css');
Application.Run;
end.
Running the above examples would insert the following line of code into the <head>
tag on your page:
<link id="MyCSS" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">