Language:English

Guide · WinCC Unified scripting

WinCC Unified scripting best practices: JavaScript that stays fast and readable

Screen objects

waiting 0

The one script thread of all screens

…

112 runs per second134 % thread load

Trace

Queue empty, screens respond

All the scripts of your screens share one thread. Add objects with a 250 ms cycle and watch the queue; switch to tag triggers and it calms down. Illustrative timings: every device is different.

The best line of JavaScript in a WinCC Unified project is the one you never had to write. The second best is short, triggered by a tag, and tells you what it did. Here is how Siemens itself says to get there, with examples you can copy.

  • Ten habits taken from Siemens' engineering guideline and style guide
  • Before and after code, ready to paste into TIA Portal
  • A checklist to run before you download to the panel
Start reading

HMIx team10 min readUpdated

First question: do you need a script at all?

Siemens' own order of preference, and a quick way to apply it

It sounds odd in a scripting guide, but it is the advice that saves the most CPU. In its engineering guideline for WinCC Unified, Siemens is blunt: tag dynamization first, then expressions, and “try to avoid script dynamizations” Siemens EG. A dynamization by tag or by expression is evaluated by the system; a script goes into a queue with every other script of the screen.

So before opening the script editor, run your idea through five questions. Most of the time you stop before the last one.

Fig. 1

Do I need a script? Five questions

  1. 01Is it a tag value shown as it is: a number, a text, a bar?

Based on Siemens' decision aid (Tips and Tricks for Scripting, fig. 2-1) and the engineering guideline's order of dynamizations.

There is one honest exception. Siemens itself says a script is the better choice when it replaces several overlapping screen objects. That is also where a dynamic SVG shines: one symbol with a parameter for its state, instead of four lamps stacked on top of each other and a script deciding which one is visible.

Know where your script runs

One thread for every screen, another for the Scheduler, and walls between them

WinCC Unified runs scripts on the server, in Node.js processes that are single-threaded. There are exactly two: one for everything that happens in screens, one for the tasks of the Scheduler Siemens Tips §2.5. A slow script in a screen delays every other script of every screen, on every client.

Fig. 2

Where each script lives

WinCC Unified Runtime · server

Process 1 · scripts of every screen

Client 1 · Screen_1

Client 2 · Screen_1

Process 2 · Scheduler tasks

Global modules: imported by each context

Tap a context

Event scripts react to clicks, Loaded, Unloaded. Their global definition is their own copy: property scripts never see it.

Each screen has two script contexts, properties and events, with their own copies of the variables. All tasks share one context. Global modules are imported by each of them.

Three consequences you will meet sooner or later. A JavaScript variable written in an event is invisible to the property scripts of the same screen. A task cannot touch a screen, because it has none (we explain the fix in opening a pop-up from the PLC). And a file written by a script lands on the device that runs the Runtime, never on the PC of the operator who clicked.

Let the tag call you, not the clock

Cyclic triggers are the most expensive habit in Unified projects

A cycle of 250 ms means four runs per second per object, whether anything changed or not. Siemens says it plainly: “Avoid cyclic triggers and use tag triggers instead”, and if you really need something cyclic, put it in the Task Scheduler, which runs in its own process Siemens EG.

Avoid· Polls every 250 ms, three separate reads

// Text "Txt_PumpState" > Text > Script. Trigger: cycle T250msexport function Txt_PumpState_Text_Trigger(item) {  const fault = Tags('Pump1_Fault').Read();  const running = Tags('Pump1_Running').Read();  const speed = Tags('Pump1_Speed').Read();  if (fault) {    return 'FAULT';  }  return running ? 'RUN ' + speed + ' rpm' : 'STOP';}

Do this· Runs only when one of its tags changes, one read

// Same text. Trigger: Tags > Pump1_Fault, Pump1_Running, Pump1_Speedexport function Txt_PumpState_Text_Trigger(item) {  const pump = Tags.CreateTagSet(['Pump1_Fault', 'Pump1_Running', 'Pump1_Speed']);  pump.Read();  if (pump.Item('Pump1_Fault').Value) {    return 'FAULT';  }  if (pump.Item('Pump1_Running').Value) {    return 'RUN ' + pump.Item('Pump1_Speed').Value + ' rpm';  }  return 'STOP';}
  1. One trigger tag, one script. If two scripts react to the same tag, merge them; Siemens recommends it, and one central script on a screen property is easier to find.
  2. Beware of “Tags (automatic)”. It adds every tag the script reads as a trigger. With a write in the script, it is a shortcut to an endless loop.
  3. Never write the tag that triggers you. Siemens: “A script triggered by a tag is not allowed to write to this tag.”

Read once, write once

TagSet, and the trap of reading what you just wrote

Every Tags('…').Read() is a request to the tag management. Four reads are four requests. A TagSet asks once for all of them, and Siemens lists it in its performance rules Siemens Tips §5.3.

Fig. 3

Four reads or one TagSet

4 × Read()

ScriptTagmanagement

4 requests

1 TagSet

ScriptTagmanagement

1 request

Each arrow is a request from the script to the tag management. Illustrative: what counts is how many there are.

The other half of the rule: do not read a tag right after writing it. The write goes to the PLC and the tag image catches up later, so the read “will normally return the old value” Siemens Tips §2.6.3. You already know the value you wrote: use it.

Avoid· Shows the value from before the write

Tags('Oven_Setpoint').Write(180);const shown = Tags('Oven_Setpoint').Read(); // still the OLD valueScreen.Items('Txt_Confirm').Text = 'Setpoint: ' + shown;

Do this· Shows the value it wrote

const setpoint = 180;Tags('Oven_Setpoint').Write(setpoint);// You already know what you wrote: show that, not a new read.Screen.Items('Txt_Confirm').Text = 'Setpoint: ' + setpoint;

Ready-to-use script

Apply a set of setpoints in one write

Checks four setpoints against their limits, writes them in a single TagSet call, waits for the PLC's answer and tells the operator which one failed, if any. Commented line by line.

Where it goes
Button > Events > Click left mouse button
Runs on
WinCC Unified V16 or later

Do this· hmix-apply-setpoints-tagset.js

// [HMI tag, value to write, lowest allowed, highest allowed]const RECIPE = [  ['Line1_SpeedSetpoint', 1450, 0, 3000],  ['Line1_TempSetpoint', 72.5, 20, 95],  ['Line1_PressureSetpoint', 3.2, 0, 6],  ['Line1_BatchSize', 500, 1, 2000]];const WAIT_FOR_PLC = 1; // hmiWriteWait: fills LastError for every tag​// 1. Never send a value the process cannot take.const outOfRange = RECIPE.filter((row) => row[1] < row[2] || row[1] > row[3]);if (outOfRange.length > 0) {  const names = outOfRange.map((row) => row[0]).join(', ');  HMIRuntime.Trace('[Recipe] Nothing written. Out of range: ' + names);  Tags('Recipe_Status').Write('Nothing written. Check: ' + names);  return;

Asynchronous, without surprises

Files, databases, logs and alarms answer later. Always handle the answer.

Reading a file, a logged value or a database does not return the data; it returns a Promise that is fulfilled later. Assign it to a text and the operator sees [object Promise]. Forget the .catch and a failure vanishes without a trace.

Do this· Read a file: answer in then, failure in catch

HMIRuntime.FileSystem.ReadFile('C:\\Users\\Public\\recipe.txt', 'utf8')  .then((text) => {    Screen.Items('Txt_Recipe').Text = text;  })  .catch((reason) => {    // Every promise gets a catch: an error code becomes words.    HMIRuntime.Trace('[Recipe] read failed: ' +      HMIRuntime.GetDetailedErrorDescription(reason));  });
  1. Always a catch. HMIRuntime.GetDetailedErrorDescription() (V18 and later) turns the error code or error object into words.
  2. Several slow calls? Start them together with Promise.all, as Siemens suggests, instead of waiting for each in turn.
  3. Property scripts return a value. Up to V19 Update 1 a property script cannot return the result of an asynchronous call; from V19 Update 2, return works in asynchronous scripts. Otherwise, write the result into a tag and bind the property to it.

Keep heavy calls off screen loading

What Siemens says never to put in Loaded or in a cycle

Some functions work hard for every call. Siemens names them in its engineering guideline and asks not to use them in a screen's Loaded event or with a cyclic trigger, but on a button click or in a scheduled task Siemens EG:

  1. Alarm subscriptions and GetActiveAlarms
  2. Reading the alarm log or logged tags
  3. ReadFile and Browse on the file system
  4. Reading electronic records

Two more from the same page: when the object is on the same screen as the script, use Screen.Items('Name'), not Screen.FindItem(); and read several texts of a text list at once instead of looping. Also remember that, while a screen loads, Siemens warns “there is no deterministic order” between dynamizations and the Loaded script.

Write it once: global modules

The same three lines in twelve screens is twelve places to fix

Logic you need in more than one place belongs in a global module (Scripts > Global modules). Each module has its own namespace and is imported in the Global definition of the screen or of the Scheduler.

Example· The module

// Scripts > Global modules > "Units"export function celsiusToFahrenheit(celsius) {  return celsius * 1.8 + 32;}

Do this· Using it in a screen

// Screen > Events > Global definition (once per screen and context)import * as units from 'Units';​// ...then in any event script of that screen:const oven = Tags('Oven_Temp').Read();Screen.Items('Txt_OvenF').Text = units.celsiusToFahrenheit(oven).toFixed(1) + ' °F';

For reuse across projects, turn the module into a script module type in a library. Its lowest device version decides which Runtime versions can use it.

Code your colleague can read at 3 a.m.

The essentials of Siemens' JavaScript style guide for WinCC Unified

Siemens publishes a programming style guide for JavaScript in WinCC Unified, based on ESLint rules Siemens SG. You do not need all of it. These are the rules that prevent real bugs. Tap a mark to see which rule it breaks.

Fig. 4

Seven rules, one short script

 ()state2) Screen.Items("Lamp_Motor").BackColor=0xFF00C000 (state==3){Screen.Items("Lamp_Motor").BackColor=0xFFE00000}

1 · ST008

Declare with const by default, let when the value changes. var is outdated.

Tap a number

Rule numbers from Siemens' style guide (entry 109758536).

Two habits outside the style guide pay off just as much: name objects in TIA after what they are (Lamp_Motor, not Circle_17), and write comments in English, which is what everyone who maintains the project after you will understand.

Make every script say what it did

Trace on purpose, catch every error, switch the tools off in production

alert() does not exist in WinCC Unified and console.log goes nowhere you can see. The tool is HMIRuntime.Trace(), read in the RTIL Trace Viewer under Subsystem > ScriptFW Siemens. Put the place in the message, so one line tells you who spoke.

  1. A few deliberate traces, not one per line. Siemens' rule DD001: remove the unnecessary ones when you finish.
  2. try…catch around what can fail, and a .catch on every promise.
  3. Debugger off in production. Siemens: it “can endanger system stability and security”.
  4. New in V21.1: a Script diagnostics view in the system diagnostics control lists script errors, overloads and your traces right on the screen.

Not sure what you are reading in the Trace Viewer? Our guide to the most common script errors decodes the messages one by one.

Before you download: twelve checks

Copy it into your commissioning notes

0 / 12

Three ways HMIx saves you the trial and error

  1. 01

    Describe what the script must do. HMIx asks for your tags, writes it, explains it part by part and simulates it.

  2. 02

    Paste a script you already have. HMIx explains it and flags, for free, the classic errors.

  3. 03

    Something fails? HMIx walks you through the checks, from the trace message to the fix.

Frequently asked questions

Are scripts bad for WinCC Unified performance?

Not by themselves. What costs performance is scripts with short cyclic triggers, many separate tag reads and heavy calls during screen loading. Siemens recommends dynamizing by tag or expression first, using tag triggers and TagSets, and moving necessary cyclic work to the Task Scheduler.

Which JavaScript version does WinCC Unified use?

Scripts run on the server in Node.js with the Google V8 engine. Siemens' style guide states that it largely implements ECMAScript 2015 (ES6): let, const, arrow functions, template strings, promises and for…of are available. Browser objects such as window, document, alert or fetch are not.

What is the minimum cycle time for a script in WinCC Unified?

It depends on the version: the V16 manual gave 100 ms and the V17 manual 500 ms as the smallest cycle in Runtime Unified. In any case, Siemens advises avoiding cyclic triggers for scripts and using tag triggers instead.

Where should I put code I need in several screens?

In a global module (Scripts > Global modules), imported in the Global definition of each screen or of the Scheduler. To reuse it across projects, create a script module type in a library.

How do I debug a WinCC Unified script?

Write HMIRuntime.Trace() messages and read them in the RTIL Trace Viewer (Subsystem > ScriptFW). On a PC Runtime you can also enable the script debugger in SIMATIC Runtime Manager and open it in Chrome; from V19 Update 2 there is a Visual Studio Code extension, and V21.1 adds a Script diagnostics view.

Can HMIx write WinCC Unified scripts for me?

Yes. Describe what the script must do and HMIx asks for your tag and object names and what starts it, writes the script, explains it part by part and simulates it in the browser when the script allows it. You can also paste a script you already have to get it explained and checked. It works with the free plan.

Ready to use, from the HMIx catalogue

Free to download: this article’s script, shared from HMIx, and controls for the screen around it.

Browse the free catalogue →

Sources

Every Siemens statement in this article was read in the document linked here. Versions and behaviour can change with updates: check the manual of your own version.

  1. Siemens: Engineering guideline for WinCC Unified, entry 109827603, V4.0 (11/2025)
  2. Siemens: SIMATIC WinCC Unified Tips and Tricks for Scripting (JavaScript), entry 109758536, V5.0 (09/2025)
  3. Siemens: Programming style guide for JavaScript in SIMATIC WinCC Unified, entry 109758536
  4. Siemens: Runtime scripting, General information (WinCC Unified V21.1)
  5. Siemens: Tracing with the RTIL Trace Viewer (WinCC Unified V21.1)
  6. Siemens: Enabling the debugger (WinCC Unified V21.1)
  7. Siemens: Configuring script diagnostics (WinCC Unified V21.1)
  8. Siemens: TagSet.Write() (WinCC Unified V21.1 object model)
  • WinCC Unified scripting
  • WinCC Unified JavaScript
  • best practices
  • TagSet
  • tag trigger
  • global modules
  • TIA Portal
  • HMIRuntime