I need to develop a Javascript Widget (almost finished), and by integrating it into the first site I found a few issues. My Widget needs to load a few libraries (jquery, jquery ui, mustache, ...); it is performed by injecting new script tags into the site with this function:
loadFile: function (filename, filetype) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
} else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref != "undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
Is this good practice? The problem now comes from the fact that the hosting page of the widget might already have jquery and jquery-ui loaded. What can I do about it without having to change my code to much? I already found this page which describes a solution for jquery. But what about jQuery-ui? I currently have the problem, that my datepickers do not work, as the site already contains datepickers and jquery-ui. Can I change my widget so that my loaded javascript files do not interfear with the including site? And also make it possible to have two instances of the widget on the same site? For the css stuff I already have a solution by creating a diff with a specific Id around the widget content and use that Id in all Css selectors.
So my main concern is about loading my libraries, having them all available in the right version. My widget should not have any impact on the hosting site and vice versa. I might include jquery, but the site might use the $ for anything else.
I already thought about using Basket Js to perform the javascript loading, but this does not solve the injection issue.
Is there a nice way to include all my libraries into my widget.js without loading external resources? So that i can use § for my internal jquery? This must be a general solution working with all types of JS libraries.
I also found this but it only works with jQuery and not other libraries.
Any best practices for such a solution?