Sometimes as a developer, the most elegant solution is the one that works. Recently, I was faced with the challenge of attempting to get JavaScript code to run consistently on certain pages in a SharePoint Online site.
Certain aspects of the project dictated that JavaScript Injection via a SharePoint hosted app was the only alternative to add the code to the site. I started with the Core.EmbedJavaScriptJSOM project from the Office365 Developers Patterns and Practices site on GitHub. This works really well if you are referencing a single JS reference file such as the jQuery library; however, I was unable to figure out how to get it to work with multiple file references, which was crucial in my case.
I won’t bore you with all of methods that I tried that didn’t work and will just say that after several fairly frustrating hours of trial and error, the pattern below is what eventually did work. I’m still using the core of the Core.EmbedJavaScriptJSOM app and have just modified the RemoteManager_Inject function in the Content/scenario1.js file ( file which is attached) to handle making sure all of the necessary JS files were loaded before my code was executed. Also, many thanks to David Husdon and his jquery-getscripts solution which I have leveraged, as well.
Although my solution works, it doesn’t seem to pass the elegance eye-test and I welcome any comments on things that may have been missed or can be improved.
Here is the file that contains the above code: