I have developed the following javascript code for creating "widgets" that a third party site can paste onto their page and load content from our web application. Everything is working, and I am in the process of thoroughly testing before we present it for use to our clients (as we don't want any issues to occur that would negatively affect their sites, or any changes to be required on our end that would cause them to have to re-paste the code).
The code which a client includes on their page is:
<script src="/widgets/widget-script.js"></script>
<script>document.addEventListener("DOMContentLoaded",
function(){UniqueWidgetName.init(["arg1", "arg2"]);});</script>
<div class="unique-widget-name-container"></div>
And the code contained within widget-script.js
is as followed (this is just a basic template void of any business logic):
var UniqueWidgetName = UniqueWidgetName || (function(window, document){ "use strict";
var _args = {};
var jQuery, $;
var url = "https://yoursite.com";
function main(){
// load required css
loadCSS(url + "/widgets/your.css");
// business logic here including usage of loaded jquery version,
// usually involves doing an ajax call to obtain some data
// and place it within the 'unique-widget-name-container' div
}
function loadCSS(url){
var css_link = $('<link>',{
rel: "stylesheet",
type: "text/css",
href: url
});
css_link.appendTo('head');
}
function loadScript(url, callback){
var scriptTag = document.createElement('script');
scriptTag.setAttribute("src", url);
if(typeof callback !== 'undefined'){
if(scriptTag.readyState){ // for older ie versions
scriptTag.onreadystatechange = function(){
if(this.readyState === 'complete' || this.readyState === 'loaded'){
callback();
}
};
} else {
scriptTag.onload = callback;
}
}
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
}
return {
init: function(Args){
_args = Args;
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js", function(){
// restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variables
$ = jQuery = window.jQuery.noConflict(true);
main();
});
}
};
/* END OF LIBRARY
*******************************************************************************/
})(window, document);
My main concern at this point is dealing with jquery conflicts. I believe the way I have implemented jQuery.noConflict()
should resolve this potential issue, but
I wanted someone else to confirm this before a production deployment.
Also, does anything else jump out as being a potential issue? Is there anything you would do differently?
business logic here including usage of loaded jquery version, usually involves doing an ajax call to obtain some data and place it within the 'unique-widget-name-container' div
Do you really need jQuery? \$\endgroup\$