Tuesday, July 12, 2016

Optimized XPages AMD fix

Recently, I had to use this fix for one of my projects. If you have done anything with Bootstrap in XPages, you have probably used this fix at least once. The one drawback with Kranenburg's design is that the snippet can only be used in the xp:resource section, which adds it to the top of the page. A common pattern is to load scripts at the end of the page to increase the speed of loading the page content. This pattern is used by many modern web sites. With this code snippet, you can use the AMD fix and load your client scripts using the optimized pattern with the benefits of fast loading times for your XPages.
<!-- Optimized Kranenburg AMD Fix Snippet -->
<!-- Original at: https://openntf.org/xsnippets.nsf/snippet.xsp?id=hack-to-use-jquery-amd-widgets-and-dojo-together -->
<xp:text escape="false">
<xp:this.value><![CDATA[
<script>
${javascript:"if (typeof define === 'function' && define.amd) {if(define.amd.vendor =='dojotoolkit.org'){define._amd = define.amd;delete define.amd;}}";}
</script>
]]>
</xp:this.value>
</xp:text>
<!-- Adding custom jquery version to load a custom plugin from another bootstrap version :P -->
<!-- gentelella jquery -->
<script src="gentelella/vendors/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Tab -->
<script src="gentelella/vendors/bootstrap/js/tab.js"></script>
<!-- Strip out the newly loaded jQuery to safely continue page generation -->
<!-- Use this dom element object later to utilize the plugin with the correct jQuery version -->
<script>
var dom = {};
dom.gQuery = jQuery.noConflict(true);
</script>
<!-- Restore dojo AMD per the original pattern -->
<xp:text escape="false">
<xp:this.value><![CDATA[
<script>
${javascript:"if (typeof define === 'function' && define._amd) {define.amd = define._amd; delete define._amd;}"}
</script>
]]>
</xp:this.value>
</xp:text>
<!-- /Optimized Kranenburg AMD Fix Snippet -->