Best way to run code from newly added JS files by snippets #336
-
Hey 👋 , Lets assume we want to load external file and run a code from this particular file. Interesting example is Google Maps API and displaying map in "Contact" page. We don't want to load Maps API for the whole application - only for "Contact" subpage and only when user wants to truly see that map. Example code (not Google Maps API but for simplicity it only outputs text to some HTML node) may looks like this.
Subpage "Contact" (e.g.
File map.js contains:
After ajax request to "Contact" page file I know that this should be done via extension but I didn't find good working solution to achieve this behavior yet. Many thanks for your answers and great work on this library 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello, I'm sorry you find the documentation lacking, but I'm afraid there's really not much more to it than what it already says 😟 As for loading third-party scripts, it's more convenient to implement it in an extension. Usually, third-party scripts pollute the global scope, so it's best to check for the existence of the API and load the script if it's not there. You can draw some inspiration from how I load Facebook SDK (beware, it uses Naja 1). I also have an idea how to improve the current behaviour: the |
Beta Was this translation helpful? Give feedback.
Hello, I'm sorry you find the documentation lacking, but I'm afraid there's really not much more to it than what it already says 😟
As for loading third-party scripts, it's more convenient to implement it in an extension. Usually, third-party scripts pollute the global scope, so it's best to check for the existence of the API and load the script if it's not there. You can draw some inspiration from how I load Facebook SDK (beware, it uses Naja 1).
I also have an idea how to improve the current behaviour: the
ScriptLoader
could deduplicate loaded scripts by theirid
if present. I think that could help your use case. Would do you think?