When working with existing sites or content management systems, you have little say on where and when jQuery is loaded. To complicate matters, some pages may have jQuery auto-loaded, and others may not (yay for performance boosts, nay for client-side plugins). Do you bite the bullet and write unmanageable scripts? Or do you believe in RequireJS and dodge the bullet matrix-style? Let me show you how.
Where does ‘jquery’ come from? That is the path alias or module name you set up in the RequireJS config. This will allow it to asynchronously load jQuery when requested by this name, then pass it in as a parameter in the function for you to use (the parameter here is “$” but can be anything).
So when creating “paths” aliases in your main.js, put a condition in there to test if jQuery has been loaded or not. Then you can return the existing jQuery object or load up your own. You can even require a minimum version of jQuery if you like. Check this out:
However, with Sitefinity it makes sense to load it directly underneath it’s auto-loaded jQuery. This way, your RequireJS modules will work in the page designer too. The way to do this is to link require.js and main.js after the opening <form /> tag. This is because Sitefinity inserts its own jQuery as the first control in the <form />. With this assumption, you can do this:
You can also do this in the code-behind somewhere:
With this code, it using the script manager Sitefinity uses and adds jQuery, then all the script references AFTER (as they appear in your code). The PageManager.ConfigureManager will not add jQuery again if it was already loaded.
Then on the frontend (for both of the cases above), it will get rendered like this:
In this example, the jQuery condition in main.js will usually find jQuery loaded by Sitefinity and reuse the object. However, on the pages where Sitefinity “doesn’t need” jQuery, RequireJS will asynchronously load the jQuery file from the path you specified. Either way, ONE jQuery is served to all your modules and self-contained. No more wiping out each other’s jQuery plugin namespace!
Latest posts by Falafel Posts (see all)
- Matching Complex Query String Rewrite Rule in IIS - March 22, 2017
- Using Google Services in UWP C# Apps – Part 2 - February 7, 2017
- Using Google Services in UWP C# Apps – Part 1 - February 6, 2017
- Redis Caching in the Google Cloud Platform - February 3, 2017
- Entity Framework with Google Cloud SQL - February 2, 2017