I am trying to create a Javascript file that I can reference from other domains that will allow the look and feel of a user’s page to be changed.
For example, The javascript file (www.mywebsite.com/123.js) would be referenced on http://www.userwebsite.com and could contain the below:
var thebody = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
var txtNode = document.createTextNode("Hello. This is a new node.");
var divIdName = "mydiv";
var csslink = "http://www.anotherwebsite.com/style.css";
var newcss = document.createElement('link');
newcss.setAttribute('href',csslink);
newcss.setAttribute('rel','stylesheet');
newcss.setAttribute('type','text/css');
newdiv.setAttribute('id',divIdName);
newdiv.appendChild(txtNode);
thebody.appendChild(newdiv);
thebody.appendChild(newcss);
Which would insert a reference to a CSS file hosted on the user’s website as well as add a new div to the DOM with the text node “Hello. This is a new node.”
I want the user to be able to login to a CMS (that I will build) so they can change the text that gets printed to the page without having to change the Javascript file that I give to them. The CMS would be hosted on my website.
What is the best practice to do this?
Obviously I could edit the javascript file remotely without the user needing to change anything – but is that the best method of updating the script?
I was thinking of having an Ajax request in the javascript that retrieves output from a php file referencing a mysql database with the text the user wants to change to – however, the same origin policy means that isn’t possible.
Thanks
You don’t need to use AJAX to retrieve the PHP output; get the clients to add a
<script />tag to their pages with thesrcattribute set to your PHP output; just make sure your script emits valid JavaScript.As your web server now thinks it’s in PHP land rather than JS assets, be sure to emit correct page headers; MIME type and expires spring to mind.
Furthermore, be aware of the un-reliable, and “hostile” environment your script will be executing in. You should minimize the amount of global variables your JavaScript script declares to mitigate the risks of collisions. The easiest way to do this is to wrap your code in an IIFE;
You should also consider prefixing your CSS classes, element ID’s etc to minimize collisions with the hosts naming schemes.