Fair enough, let’s see a couple of ways to tackle this specific problem. But first, let me clarify a couple of aspects.
What do you mean?
This technique is about loading a piece of code without incurring in the cost of parsing and execution. This also prevents the code to pollute the global scope or to compute unwanted results, before its time.
When can it be useful?
Generally, it can be useful to have more granular control over what gets executed and when, since scripts execution can potentially block the main thread and mess up with your app’s responsiveness. Here are a couple of use case scenarios that come to mind:
How can it be done?
There a couple of techniques. As it often happens, there is the standard non-broadly-supported way, and the hacky way. Let’s see both.
new Image().src = “…”is the hacky way. Basically, the browser will fetch the script, then detect that it is not a valid image format and throw and error event. Nothing should happen, but you should have your script in the browser’s cache. Now you can — for example in the onerror handler — simply request it in a regular
<script src=”…”> tag.
<object data=”…”>. This one I never tried, but according to this piece by the great Stoyan Stefanov, it should work just fine!
If you’ve found this post useful at all, press the ❤ button! I read each and every comment, so be sure to contribute to the conversation with your thoughts!