Consider scenarios where you have pages composed of parts that are combined at runtime. If the many authors of those parts have external script references sprinkeled throughout, there is the chance that author2 might over write author1’s reference of JQuery or some other script dependency. The consequences of doing this are usually breakage. I wrote this little script to allow all authors to call their scripts into page parts safely, ensuring that a script or stylesheet reference never overwrites another. This script assumes that URI is sufficient to uniquely identify a script. It does not attempt to deal with the situation where 2 developers might both load the same library from different URIs.
DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>title>
<script type=”text/javascript”>
/**
* Function object to carry DOM management behaviors
*/
function bootStrapper() {
var head = document.getElementsByTagName(“head”)[0];
/**
* Loads an external javascript source by creating a
2 responses to “A Small Javascript To Safely Load Scripts and Styles Into The DOM”
-
function addStyleReference(s,n,d) {//url,id,docOrcontentdoc
if(s){
d=d?d:document;
var k=”link”;h=d.getElementsByTagName(“head”)[0];
if(!isLoaded(h,k,”href”,s)){
var e=d.createElement(k);if(n){e.id=n};
e.href=s;e.rel=”stylesheet”;e.type=”text/css”;
h.appendChild(e);
}
};
};-
function isPresent(e,n,k,v) {//container, tagName, propKey, propValue
var m=e.getElementsByTagName(n),r=false,i;
for (i=0,i<m.length; i++){if(m[i][k] == v){r=true;break}}
return r;
};function addStyleReference(s,n,d) {//url,id,docOrcontentdoc
if(s){
d=d?d:document;
var k="link";h=d.getElementsByTagName("head")[0];
if(!isPresent(h,k,"href",s)){
var e=d.createElement(k);if(n){e.id=n};
e.href=s;e.rel="stylesheet";e.type="text/css";
h.appendChild(e);
}
};
};
-
Leave a Reply