It's better to use following approach.
In any component that require some onLoad action to be performed add following method:
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(
OnDomReadyHeaderItem.forScript("alert('REPLACE ALERT BY YOUR SCRIPT')"));
}
If you need to prepare script dynamically with extra params and etc. I recommend following:
private final static TextTemplate template
= new PackageTextTemplate(YourComponentOrPage.class, "your-js-template.js");
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
Map<String, Object> params =new HashMap<String, Object>();
params.put("parameter1", parameter1Value);
params.put("parameter2", parameter2Value);
response.render(OnDomReadyHeaderItem.forScript(template.asString(params)));
}
And "your-js-template.js" may look like:
alert('Hi!, ${parameter1}. My name is ${parameter2}');