random quote from array in external javascript not displaying onload - javascript

I'm a javascript beginner, and I'm trying to figure out why this code works when written in the head, but not when it's being referenced from an external file.
in the head of my html document, I'm referencing the javascript file "quote.js" as follows.
<script type="text/javascript" language="JavaScript" src="/js/quote.js"> </script>
the contents of quote.js are as follows
var textarray = [
"Be Good.",
"Our future depends powerfully on how well we understand the cosmos.",
"Bottomless wonders spring from simple rules... repeated without end.",
"All our science, measured against reality, is primitive and childlike — and yet, it is the most precious thing we have.",
"To use violence is to already be defeated."
];
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('ShowText').innerHTML=textarray[rannum];
}
window.onload = function() { RndText(); }
finally, the div I'm replacing in the body is as follows...
<div id = "ShowText"></div>
it's probably a stupid mistake, but I've been trying to track it down for a while now, and I'm missing something. When I write the contents of quote.js in my html head, it works fine. Any ideas? Thanks in advance.

If the code works in the head, but not when included, it's likely to be a problem with the path to the script. Double check that /js/quote.js is an appropriate location. It may need to be js/quote.js, you you may have a typo. In browsers like FireFox and Chrome, if you view the source code of your page you can click on the path to files like this and it loads the included file or shows you an error if the file is not found.
If you can share a link to the page, I can tell you with more certainty exactly what the problem is.
Also, you don't have to the language attribute if you're using XHTML, but that's not causing the problem.

Perhaps the code is running before the DOM is ready
Instead of onload use the event DOMContentLoaded
document.addEventListener('DOMContentLoaded', function () {
//code here
}, false);

Related

Edit a <script> tag in the <head> before it loads and runs the script

I am on an e-commerce platform where I can edit the <head>, however some things that are injected into the head are out of reach for users. So even though we can edit the <head>, there are injections which are out of reach and therefore unremovable via the traditional method.
PS: I can put script before or after these injected JS script tags, which are generated and populated along with my scripts. And so my script would run before the injected tags if I place my script before their "tag injection line."
The Problem
The problem is, this platform started injecting analytics and spam into the head, basically jacking our customers info and selling it to third parties. So I want to disable their crappy scripts.
<script type="text/javascript" async="" src="/some.JS.file.min.js"></script>
<script type="text/javascript" async="" src="/another.JS.file.min.js"></script>
The Question
Is it possible with javascript or jquery to write a script that will edit tags before they run? I can insert this custom script before the tags are in injected. I was wrong -- the unwanted <script> tags are always PREpended to the first non-commented <script> tag, and so no javascript will work to hack up the tags before they run.
What I Have Tried So Far
I found this incomplete and not working answer from this SO question.
When I run the full script with the right details entered for my own site, I get so many errors it's difficult to know where to begin as I have no idea what all the XHR stuff is for or what it does, and some of the errors are ones I've never even seen before.
When I run just this part, which I somewhat understand:
doc = document.implementation.createHTMLDocument(""+(document.title || ""));
scripts = doc.getElementsByTagName("script");
//Modify scripts as you please
[].forEach.call( scripts, function( script ) {
if(script.getAttribute("src") == "/some.JS.file.min.js"
|| script.getAttribute("src") == "/another.JS.file.min.js") {
script.removeAttribute("src");
}
});
EDIT UPDATE:
Their script is inserted AFTER my scripts. That is, I can insert the script into the <head> before their script tags or after. We are looking into new platforms now but I still need to solve this in the meantime as it will be months before we switch. I was hoping g there is some JavaScript I am not aware of that can edit HTML script tags before they run, if this script runs before they do.
EDIT 2:
Nit's answer window.bcanalytics = function () {}; works great and breaks most of it by breaking window.bcanalytics.push but somehow some of it still survives.
In this block:
<script type="text/javascript">
(function() {
window.bcanalytics || (window.bcanalytics = []), window.bcanalytics.methods = ["debug", "identify", "track",
"trackLink", "trackForm", "trackClick", "trackSubmit", "page", "pageview", "ab", "alias", "ready", "group",
"on", "once", "off", "initialize"], window.bcanalytics.factory = function(a) {
return function()
{
var b = Array.prototype.slice.call(arguments);
return b.unshift(a), window.bcanalytics.push(b),
window.bcanalytics
}
};
for (var i = 0; i < window.bcanalytics.methods.length; i++)
{
var method = window.bcanalytics.methods[i];
window.bcanalytics[method] = window.bcanalytics.factory(method)
}
window.bcanalytics.load = function() {
var a = document.createElement("script");
a.type = "text/javascript",
a.async = !0, a.src = "http://cdn5.bigcommerce.com/r-2b2d3f12176a8a1ca3cbd41bddc9621d2657d707/app/assets/js/vendor/bigcommerce/analytics.min.js";
var b = document.getElementsByTagName("script")[0];
// This line still runs and loads analytics.min.js
// This line still runs and loads analytics.min.js
// This line still runs and loads analytics.min.js
b.parentNode.insertBefore(a, b)
// ^^^ This line still runs and loads analytics.min.js
// This line still runs and loads analytics.min.js
// This line still runs and loads analytics.min.js
}, window.bcanalytics.SNIPPET_VERSION = "2.0.8", window.bcanalytics.load();
bcanalytics.initialize({"Fornax": {"host": "https:\/\/analytics.bigcommerce.com","cdn": "http:\/\/cdn5.bigcommerce.com\/r-2b2d3f12176a8a1ca3cbd41bddc9621d2657d707\/app\/assets\/js\/vendor\/bigcommerce\/fornax.min.js","defaultEventProperties": {"storeId": 729188,"experiments": {"shipping.eldorado.ng-shipment.recharge-postage": "on","shipping.eldorado.label_method": "on","cp2.lightsaber": "on","PMO-272.cp1_new_product_options": "on","cart.limit_number_of_unique_items": "control","cart.auto_remove_items_over_limit": "control","BIG-15465.limit_flash_messages": "control","BIG-15230.sunset_design_mode": "control","bigpay.checkout_authorizenet.live": "on","bigpay.checkout_authorizenet.live.employee.store": "control","bigpay.checkout_authorizenet.test": "on","bigpay.checkout_authorizenet.test.employee.store": "control","bigpay.checkout_stripe.live": "on","bigpay.checkout_stripe.live.employee.store": "control","bigpay.checkout_stripe.test": "on","bigpay.checkout_stripe.test.employee.store": "control","sessions.flexible_storage": "on","PMO-439.ng_payments.phase1": "control","PMO-515.ng_payments.phase2": "control","PROJECT-331.pos_manager": "control","PROJECT-453.enterprise_apps": "control","shopping.checkout.cart_to_paid": "legacy_ui","onboarding.initial_user_flow.autoprovision": "on","faceted_search.enabled": "off","faceted_search.displayed": "off","themes.previewer": "enabled"}},"defaultContext": {"source": "Bigcommerce Storefront"},"anonymousId": "24a35a36-7153-447e-b784-c3203670f644"}});
})();
</script>
window.bcanalytics.load manages to survive and loads analytics.min.js (according to the Network tab), though I can't tell if the script then runs or doesn't.
Also, I've figured out that these pesky HTML lines:
<script type="text/javascript" defer="" async="" src="http://tracker.boostable.com/boost.bigcommerce.js"></script>
<script type="text/javascript" async="" defer="" src="http://cdn5.bigcommerce.com/r-2b2d3f12176a8a1ca3cbd41bddc9621d2657d707/javascript/jirafe/beacon_api.js"></script>
<script type="text/javascript" async="" src="http://cdn5.bigcommerce.com/r-2b2d3f12176a8a1ca3cbd41bddc9621d2657d707/app/assets/js/vendor/bigcommerce/analytics.min.js"></script>
<script type="text/javascript" async="" src="http://www.google-analytics.com/plugins/ua/ecommerce.js"></script>
are Always PREpended to the first non-commented <script> opening tag, so unfortunately, none of the creatively destructive methods below will work, as any script I try to insert ahead of these tags will automatically find the pesky unwanted lines appended before it.
Assuming the offending code is similar to that of the question you linked to, I would simply try to break the offending code so it fails to execute.
From hereon the answer relies on code from the other question since you didn't provide any.
The offending code relies on analytics, which is ensured on the page at the beginning of the script:
(function(){
window.analytics||(window.analytics=[]),window.analytics.methods=["debug","identify","track","trackLink","trackForm","trackClick","trackSubmit","page","pageview","ab","alias","ready","group","on","once","off","initialize"],window.analytics.factory=function(a){return function(){var b=Array.prototype.slice.call(arguments);return b.unshift(a),window.analytics.push(b),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var method=window.analytics.methods[i];window.analytics[method]=window.analytics.factory(method)}window.analytics.load=function(){var a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src="http://cdn2.bigcommerce.com/r6cb05f0157ab6c6a38c325c12cfb4eb064cc3d6f/app/assets/js/analytics.min.js";var b=document.getElementsByTagName("script")[0];b.parentNode.insertBefore(a,b)},window.analytics.SNIPPET_VERSION="2.0.8",window.analytics.load();
//The rest of the script
})();
To break the whole script and prevent it from running you should simply assign window.analytics a value that will conflict with the methods that are used.
So, for example, you could run a script before the offending script that simply assigns the following:
window.analytics = function () {};
Which will result in the offending script failing due to a type error.
If you know you can at least get your scripts to run first, one (albeit hacky) solution is to just absolutely "trash" the JS environment for the next script, so it has some problems. For example:
//trash it
document.getElementById=null;
document.querySelector=null;
document.querySelectorAll=null;
window.console=null;
window.alert=null;
document.getElementsByTagName=null;
document.getElementsByClassName=null;
As soon as the enemy script tries using one of those functions, it will just crap out. Those are just some common methods off the top of my head... find out which ones its using, and nuke those. Of course, nuking anything you need for events on your own page could be an issue.
How are the scripts being injected? If it's through something like document.createElement, you could attempt to hijack that function and disable it if the element name is script:
var origCreate = document.createElement;
document.createElement = function (name) {
if (name.toLowerCase() !== 'script') {
origCreate.call(document, name);
}
};
Since the scripts are being inserted server-side, you won't be able to disable the running of the scripts in your JavaScript. However, if you're able to inject any arbitrary text before and after the scripts being inserted, you could try commenting out the script tags by inserting this first:
<!--
...then this after:
-->
If the scripts get injected between these, it will hopefully cause the HTML parser to ignore the scripts.
Update:
Sounds like you need to disable just some of this content, so commenting everything out won't work. However, if before/after hijacking works, you could potentially wrap the injected scripts in a DOM element, parse that content, strip out the scripts you don't want, and inject the scripts so they run:
Inject something like this before:
<style id="hijack" type="text/html">
...and this after:
</style>
<script>
var hijackedWrapper = document.getElementById('hijack');
var scripts = hijackedWrapper.textContent;
scripts = scripts.replace('<script src="http://some.domain.com/foo.js"></s' + 'cript>', '');
document.write(scripts); // There's better ways to do this, but is just an illustration
</script>
Like the others, I would suggest sabotaging the js environment for the hostile script, and then recovering it back once you need it.
For example, if the script relies on document.getElementById, you can do this
var restore = {
getElementById: document.getElementById
};
document.getElementById = null;
and then if you have a need to use document.getElementById later, you can restore it back:
document.getElementById = restore.getElementById;
I also wanted to note that removing the actual script tags, as far as I can tell, is not possible:
If you put in a script before the hostile scripts, then they will not be loaded in the DOM yet, so it can't see anything to remove.
If you put in a script after the hostile scripts, the hostile scripts will already be loaded.

How do I hide javascript code in a webpage?

Is it possible to hide the Javascript code from the html of a webpage, when the source code is viewed through the browsers View Source feature?
I know it is possible to obfuscate the code, but I would prefer it being hidden from the view source feature.
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect JavaScript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your JavaScript in an external JavaScript file that is included with:
<script type="text/javascript" src="http://mydomain.example/xxxx.js"></script>
tags, then the JavaScript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external JavaScript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
Put it in an external .js file.
Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can't be read without further processing, etc...
Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
Put as much interesting logic that you want to protect on the server that you retrieve via AJAX calls rather than do local processing.
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at what you do, not by having secrets. That's ultimately how success works on the web anyway.
No, it isn't possible.
If you don't give it to the browser, then the browser doesn't have it.
If you do, then it (or an easily followed reference to it) forms part of the source.
My solution is inspired from the last comment. This is the code of invisible.html
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>
The clear code of invisible_debut.js is:
$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});
Notice that at the end I'm removing the created script.
invisible.js is:
$(document).ready(function(){
alert('try to find in the source the js script which did this alert!');
document.write('It disappeared, my dear!');});
invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.
Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.
Use Html Encrypter The part of the Head which has
<link rel="stylesheet" href="styles/css.css" type="text/css" media="screen" />
<script type="text/javascript" src="script/js.js" language="javascript"></script>
copy and paste it to HTML Encrypter and the Result will goes like this
and paste it the location where you cut the above sample
<Script Language='Javascript'>
<!-- HTML Encryption provided by iWEBTOOL.com -->
<!--
document.write(unescape('%3C%6C%69%6E%6B%20%72%65%6C%3D%22%73%74%79%6C%65%73%68%65%65%74%22%20%68%72%65%66%3D%22%73%74%79%6C%65%73%2F%63%73%73%2E%63%73%73%22%20%74%79%70%65%3D%22%74%65%78%74%2F%63%73%73%22%20%6D%65%64%69%61%3D%22%73%63%72%65%65%6E%22%20%2F%3E%0A%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%73%63%72%69%70%74%2F%6A%73%2E%6A%73%22%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%3E%3C%2F%73%63%72%69%70%74%3E%0A'));
//-->
HTML ENCRYPTER
Note: if you have a java script in your page try to export to .js file and make it like as the example above.
And Also this Encrypter is not always working in some code that will make ur website messed up... Select the best part you want to hide like for example in <form> </form>
This can be reverse by advance user but not all noob like me knows it.
Hope this will help
'Is not possible!'
Oh yes it is ....
//------------------------------
function unloadJS(scriptName) {
var head = document.getElementsByTagName('head').item(0);
var js = document.getElementById(scriptName);
js.parentNode.removeChild(js);
}
//----------------------
function unloadAllJS() {
var jsArray = new Array();
jsArray = document.getElementsByTagName('script');
for (i = 0; i < jsArray.length; i++){
if (jsArray[i].id){
unloadJS(jsArray[i].id)
}else{
jsArray[i].parentNode.removeChild(jsArray[i]);
}
}
}
I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).
If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.
I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.
For example:
In your index.php
<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>
<body>
Click me.
<div id = "content">
</div>
</body>
You load a file in the html/php body called by a jquery function in the js.js file.
js.js
function loaddiv()
{$('#content').load('content.php');}
Here's the trick.
In your content.php file put another head tag then call another js file from there.
content.php
<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>
Click me too.
<div id = "content2">
</div>
in the js2.js file create any function you want.
example:
js2.js
function loaddiv2()
{$('#content2').load('content2.php');}
content2.php
<?php
echo "Test 2";
?>
Please follow link then copy paste it in the filename of jquery.js
http://dl.dropbox.com/u/36557803/jquery.js
I hope this helps.
You could use document.write.
Without jQuery
<!DOCTYPE html>
<html>
<head><meta charset=utf-8></head>
<body onload="document.write('<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>');">
</body></html>
Or with jQuery
$(function () {
document.write("<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>")
});
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
Approach i used some years ago -
We need a jsp file , a servlet java file and a filter java file.
Give access of jsp file to user.
User type url of jsp file .
Case 1 -
Jsp file will redirect user to Servlet .
Servlet will execute core script part embedded within xxxxx.js file
and
Using Printwriter , it will render the response to user .
Meanwhile, Servlet will create a key file .
When servlet try to execute the xxxx.js file within it , Filter
will activate and will detect key file exist and hence delete key
file .
Thus one cycle is over.
In short ,key file will created by server and will be immediatly deleted by filter .
This will happen upon every hit .
Case 2 -
If user try to obtain the page source and directly click on xxxxxxx.js file , Filter will detect that key file does not exist .
It means the request has not come from any servlet. Hence , It will block the request chain .
Instead of File creation , one may use setting value in session variable .
It's possible. But it's viewable anyway.
You can make this tool for yourself:
const btn = document.querySelector('.btn');
btn.onclick = textRead;
const copy = document.querySelector('.copy');
copy.onclick = Copy;
const file = document.querySelector('.file');
file.type = 'file';
const pre = document.querySelector('.pre');
var pretxt = pre;
if (pre.innerHTML == "") {
copy.hidden = true;
}
function textRead() {
let file = document.querySelector('.file').files[0];
let read = new FileReader();
read.addEventListener('load', function(e) {
let data = e.target.result;
pre.textContent = data;
});
read.readAsDataURL(file);
copy.hidden = false;
}
function Copy() {
var text = pre;
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
}
<input class="file" />
<br>
<button class="btn">Read File</button>
<pre class="pre"></pre>
<button class="copy">Copy</button>
How to use this tool?
Create a JavaScript file.
Go in the tool and choose your JavaScript file.
Copy result.
Paste the result in Notepad.
Remove data:text/javascript;base64,.
Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.
How to view this hidden code?
Copy the hidden code and paste it in Notepad.
Copy a string that after eval and atob.
Paste data:text/javascript;base64,String and change String to your copied string.
Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
http://www.sitepoint.com/bundling-asp-net/

Dynamically loaded <script> tag not being used in WebKit browsers

It seems this is a known problem and has been asked several times before here in SO however I do not see anything specific to jQTouch so I thought I would give it a try.
jQT will dynamically load pages when a link is clicked. In this page I would like to include something like
<script>
$.include('javascriptfile.js', function() {alert('do something with results of this file to an already existing div element');};
</script>
The $.include is a jquery plugin I found that mimics the $.load with a few more smarts added to it. Tested to work on FF but not in Chrome or most importantly, Safari.
The alert is never displayed. FireBug never shows the javascript even being loaded. If I put an alert before the $.include I still do not see anything.
I have tried an onclick/ontap event that would then run this code that was included in the head tag, no luck.
Edit: I am using the r148 revision of jQT. This was working prior to moving to this version, i believe.
Did you try to add the javascript file using one of these two methods:
Static Way:
<script type="text/javascript">
function staticLoadScript(url){
document.write('<script src="', url, '" type="text/JavaScript"><\/script>');
}
staticLoadScript("javascriptfile.js");
modifyDivFn(processFnInFile());
</script>
Dynamic way:
<script type="text/javascript">
function dhtmlLoadScript(url){
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
onload = function(){
dhtmlLoadScript("javascriptfile.js");
modifyDivFn(processFnInFile());
}
</script>
After the include you can call a function that does the processing you want (that being processFnInFile()) which result will be passed to modifyDivFn (and modify the div you want.) You could do this in one function, just to illustrate the idea.
Source: Dynamically Loading Javascript Files
Well Geries, I appreciate your help but ultimately the answer required a drastic rethinking of how I was using JQTouch. The solution was to move everything to an onclick event and make all the hrefs link to #. This might be what you were talking about Geries.
In the onclick function I do the logic, preloading, loading of the page through my own GET through jquery, then use the public object jQT.goTo(div, transition). This seems to get around the WebKit bugs or whatever I was running into and this now owrks on FireFox, Chrome, Safari, iPhone, and the lot.
I do run into a few animation issues with JQT but I think these are known issues that I hope Stark and the gang at JQTouch are working on.

How to embed and call a javascript script in a RichFaces/JSF page

I've been looking around for a method to embed and call javascript functions in JSF pages. I'm also using RichFaces.
To define the function, it appears I can do this in a cross-browser supported fashion:
<a4j:outputPanel ajaxRendered="true">
<f:verbatim>
<script type="text/javascript">
function datum() {
alert("hi");
}
</script>
</f:verbatim>
</a4j:outputPanel>
but I'm not sure how I can call this function when the page loads so the text it returns is embedded in an h:outputPanel. The plan is to have a js clock embedded in the page which is served to the client. Note I'm not using the body tag, I'm using facelets ui:composition, f:view (core) and RF RI rich:page.
Thanks
Regardless of what sorts of server-side tags you're using, by the time your page gets to the browser that's all gone and it's just HTML. (At least, it had better be, or things won't work anyway.) What you need to do is arrange for your code to be called by a "load" event handler. There are various ways to do this, but the simplest would be this:
<f:verbatim>
<script type="text/javascript">
window.onload = function() {
alert("hi");
}
</script>
</f:verbatim>
Now as to initializing another part of the page, once again what matters is what ends up in the HTML. You'll want to arrange for there to be some sort of HTML container (a <div> or something, depending on your page design) and you'll want it to have a unique "id" attribute. Your Javascript can then use the "id" to find the element and set its contents:
var elem = document.getElementById("whatever");
elem.innerHTML = // ... whatever ;
You'd probably do that stuff inside the "load" function.
Also, if you're using Facelets instead of JSP, which is a XML based view technlogy, you will need to add the XML CDATA section delimiters if your JavaScript contains comments // or literals such as <, >, &&, etc. Here's the example with the XML CDATA delimiters:
<f:verbatim>
<script type="text/javascript">
//<![CDATA[
//Comments won't show error now.
window.onload = function() {
alert("hi");
}
//]]>
</script>
</f:verbatim>
You can see a thorough explanation of when to use CDATA here. You do not need those if you're creating HTML5 pages.
Happy coding!

How do I add an external js file with a parameter

I want to give a minimal js code to random websites so that they can add a widget.
The code needs to run after the main page loads and include a parameter with the domain name. ( I don't want to hardcode it)
One option is to add this code just before the </body> (so It will run after the page loads):
<script type="text/javascript" id="widget_script">
document.getElementById('widget_script').src=location.protocol.toLowerCase()+"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
</script>
This works in IE but not in Firefox. I see with Firebug that the src property is created correctly but the script from my site is not loaded.
My question is : what is the best way to do that ? (preferably by putting minimal lines on the header part.)
To further clarify the question: If I put a script on the header part, how do I make it run after it is loaded and the main page is loaded? If I use onload event in my script I may miss it because it may load after the onload event was fired.
You can try to statically include the script with document.write (is an older technique and not recommended to use as it can cause problems with more modern libraries):
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
document.write('<script src="', url, '" type="text/javascript"><\/script>');
Or with dynamically created DOM element:
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
Later edit:
To ensure the script is run after onload this can be used:
var oldWindowOnload = window.onload;
window.onload = function() {
oldWindowOnload();
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
}
I do not believe it can be shorter than this, apart from shorter variable names :)
Why not use the getScript method of jQuery to do the loading? If you don't want to be dependant on jQuery, you can trace through the source to learn how they tackled it.
Viewing a widely used library is always going to show you solutions to problems you didn't know you had. For example, you can see how jQuery manages to generate a callback when the script is loaded, and how it avoids a purported memory leak in IE.
You probably want to be implementing the non-blocking script technique. Essentially instead of modifying the src of a script, you're going to create and append a whole new script element.
Good write up here and there are standard ways to do this in YUI and jQuery. It's quite straightforward with only one gotcha which is well understood (and documented at that link).
Oh and this:
One option is to add this code just
before the </body> (so It will run
after the page loads):
...is not technically true: you're just making your script the last thing in the loading order.

Categories

Resources