replace content after scripts have been loaded

reproduce
=== test.js
```
function test() {alert(test)}
```

=== content
```
<script src='test.js' type='text/javascript'></script>
<script type='text/javascript'>test()</script>
```

=== result
```
Uncaught TypeError: undefined is not a function
```

checked in chrome and firefox.
This pull reguest is just one of the solutions to the issue.