Dynamically load Scripts that are self finding

Posted By: Ian on Feb 16, 2014 in JQuery
Last modified on January 29th, 2015 at 9:31 pm,

Q. I’m making a widget and i want the end user to only have to insert 1 line into the webpage and my script to do the rest.

A. OK well as a demonstration were going to create a simple widget (Not a true widget but you get the idea) that loads 1 JavaScript, 1 Style sheet and creates an id called widget which were then use to insert a picture of my cat Max!

1) Create a folder and call it widget
2) Inside there create 4 files index.html, loader.js, widget.js and widget.css
3) Copy the 4 files from below pasting into the appropriate files you just created above.
4) Goto http://YOURWEBSITE.COM/widget/ and try it out!

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<title>Widget Demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript" async src="http://YOURWEBSITE.COM/widget/loader.js"></script>

</head>
   <body>

  </body>
</html>

loader.js

(function (d, s, l) {
    var a = d.createElement(s),
        b = d.getElementsByTagName(s)[0],
        c = (c = d.getElementsByTagName(s)) && c[c.length - 1],
        e = d.createElement('div'),
        f = d.createElement(l);
    g = (g = c.src) && g.substring(0, g.lastIndexOf('/')) + '/';
    a.src = g + 'widget.js';
    b.parentNode.insertBefore(a, b);
    f.rel = 'stylesheet';
    f.type = 'text/css';
    f.href = g + 'widget.css';
    d.getElementsByTagName('head')[0].appendChild(f);
    e.id = 'widget';
    d.body.appendChild(e);
}(document, 'script', 'link'));

Then create widget.css and widget.js files in the widget folder
widget.js

$("#widget").prepend("");

widget.css

body {
background:#82C7EA;
}

#widget {
background:#FBFBDA;
border:#D21F07 4pt dashed;
width:320px;
display:block;
margin:0 auto;
padding:10px;
}

By inserting the full URL of the loader script this enables loader.js to get the path of itself and share it with widget.js and widget.css. : )
Try MeDownload

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125