Executing an external script when page loads

Hi,

I developed app where I need to execute an external script when page loads.

In a web page, it would look like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="toChange"></div>
<script src="externalAddress/randomId">
</script>
</body>
</html>

If I understand quite well, it is not really Angular / Ionic’s flavour.
My problem is that:

  • script address is not always the same, depending on an id. Once it could be “externalAddress/id123456” and when the page reloads it could be “externalAddress/abcdef” depending on the value of an element (the address of the script is generated by a home-made script that I can easily integrate in Ionic).
  • script must be executed each time an event is fired
  • using this script is the only one way to get access to some information for the page (no web services for examples)

What would be the Ionic way to deal with this?

I would do pretty much anything possible to try to redesign things so this isn’t needed, because it’s extremely ugly, error-prone, hard to test, and a potential vector for security nightmares.

That being said, your best bet would probably be manually inserting the script element into the DOM in a lifecycle event like ionViewDidLoad. I don’t think you would be able to achieve this with ordinary template syntax.

I totally agree with you.

Unfortunately, I have no other choice than to work with this script at least for a short period of time.
As suggested, I inserted to the DOM using an innerHTML tag. Works well but obviously, the script was never fired.

I found a first solution to launch the script once the page was loaded. It implied the use of JS ‘eval’ function… Did you say ‘ugly’?

I really did not like this solution making the app (and the consumer) vulnerable.
I found another solution.
Step 1: Use a HTTP request to get the random script (as text).
Step 2: Parse the script to find information I needed (do not execute the script).
Step 3: Inject the information to the page the Angular way (binding).

Still not the prettiest solution but could be an acceptable solution:

  • I can write a test to see if the script parser works (in order to detect if the loaded script changes)
  • I do not need to execute an external script (safer)
  • I built an error handler to be sure that the information coming from the script are safe to use or at least, won’t make the app crash.

Thank you for suggesting a solution, it helped me find this workaround.

That sounds like a very reasonable plan.

Just to clarify (and I think we’re both in agreement that this whole thing is far best avoided), when I said “I don’t think you would be able to achieve this with ordinary template syntax”, that includes [innerHTML]. What I was talking about is going over Angular’s head in a lifecycle event and jamming a new <script> element generated via document.createElement() into the DOM.