I've started using RequireJS and it works very well for new code. However we have a large portion of the app that uses in page javascript blocks that are generated serverside. I was wondering if anyone knew what the best approach is for bridging this. I'd prefer not to rewrite all the JavaScript a full client side app as it would take forever. So my question is, is there a way of running the in page stuff once RequireJS has loaded, and is there a clean way of exposing libraries described in Require to the legacy code?
i.e.
How could you adapt this to run once require had loaded:
<script type="text/javascript">alert($('#somediv').html())</scipt>
Note the jquery dependancy.
I'm really wary about what I'm about to suggest, as I think this is an unfortunate problem of things being incorrectly designed originally; you're sort of running against the basic way Javascript works. I'd really prefer to think of this kind of issue as "job security" for the person assigned to re-make this stuff as outside-of-HTML code.
But if you want to hear it, I do have a possible solution that uses eval. For that alone, I think I'm going to be downvoted, and not without good reason. I haven't even tested this (except for the 'script with alternate type' and its selection), but seeing this question had two upvotes, no answer, I figure I'll suggest it. So, you're going to have to evaluate it with its potential security risks.
Start by replacing in-page scripts with this:
<script type="text/postRequireScript">alert($('#somediv').html())</script>
Since the browser doesn't know what a "postRequireScript" is, it won't load it. Once requirejs has loaded, run this script (you could also add a 'class' to these scripts to make selecting all of them easier)
$("script[type='text/postRequireScript']").each(function() {
var scriptContent = $(this).text();
// highly recommend you do at least some sanitization on scriptContent, if you know
// what sort of things to expect from it.
eval(scriptContent);
this.type = 'text/completedScript'; // prevent script from being re-run.
});
This would need to run each time you're adding HTML that could have a script in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With