#ASKTHEINDUSTRY 31: What if I wanted to load JS without executing it?
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:
- In a medium-to-big sized app, it is a good practice to preload following routes for optimal performance. It can be harmful though, if huge scripts are fetched — and parsed and executed — in the middle of some other activity.
- Warm up the cache for features that will possibly be needed in the near future by the app. Again, lazy loading non-critical features of an app is a great way to hit great performance, but it can be useful to prepare the cache with the needed assets.
- Prepare a third-party library before it’s actually needed. For example, a complicated piece of code that helps your app to handle video streams or WebVR or WebGL. It may give a good boost to your app’s response time, if you are able to prepare those dependencies during idle times.
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.
- Link Preload. We’ve talked about it too much lately, yet it keeps coming up. I’ll keep it short: by specification, resources fetched with a Preload don’t get executed by default.
- <img src=”…”> or 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!