Load script in html based on cookie - javascript

How can I load scripts in a html based on the cookie value. I need to switch between development and deployment mode.
I am using wro4j but I can't find where the error comes in that wro4j grouped js files.
<head>
if (getcookie(debug-mode) load the following scripts
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/main-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-app.js"></script>
else load this script
<script type="text/javascript">
loadIndividualJsCssFiles('config/assets.xml');
</script>
</head>
how to acheive this

document.cookie is a string in the browser that contains all of your cookie information. A quick and dirty solution might look something like this:
function injectScript(src) {
var script = document.createElement('script');
script.src = src;
script.type = 'text/javascript';
document.body.appendChild(script);
}
if ( document.cookie.indexOf('debug-mode') > -1 ) {
injectScript("/assets/v/{{ASSET_VERSION}}/main-core.js");
injectScript("/assets/v/{{ASSET_VERSION}}/angular-core.js");
injectScript("/assets/v/{{ASSET_VERSION}}/angular-app.js");
} else {
var el = document.createElement('script');
script.type = 'text/javascript';
script.text = 'loadIndividualJsCssFiles(\'config/assets.xml\');';
document.head.appendChild(el)
}
Note: I haven't tested this myself
Basically you are just looking for an occurance of the name of the cookie you are looking for within the document.cookie string.
A more robust approach might include converting your cookie string into key-value array.

Related

Javascript to dynamically insert plugins and code

I'm trying to provide my users with a single <script> tag that will add some plugins to the page and execute some javascript code. I'm providing my users with a code snippet like this, and asking them to add it anywhere within the body of their website:
<script type="text/javascript" src="//my-domain/code?s=1a2b3c4d&t=faq&cb=1408412749" async></script>
In the response, I have the following Javascript code:
//add jquery to page
var script = document.createElement('script');
script.src = 'http://my-domain/assets/js/jquery.min.js';
document.body.appendChild(script);
//move jquery to our own namespace
var script = document.createElement('script');
script.innerText = "var SB = {};SB.$ = jQuery.noConflict(true);";
document.body.appendChild(script);
As you can see, I'm trying to add Jquery to the page, and then namespace it in case Jquery already exists. The problem is that when the code executes, I'm receiving this error:
Uncaught ReferenceError: jQuery is not defined
So, clearly jQuery is not loaded yet when the namespacing code executes, but I don't understand why. Shouldn't jQuery be defined at this point?
The script.onload function seems to have solved the problem:
//add jquery to page
var script = document.createElement('script');
script.src = 'http://my-domain/assets/js/jquery.min.js';
script.onload = function(){
//move jquery to our own namespace
var script = document.createElement('script');
script.innerText = "var SB = {};SB.$ = jQuery.noConflict(true);";
document.body.appendChild(script);
}
document.body.appendChild(script);

Include jQuery from another JavaScript file

I am trying to include jQuery from a javascript file. I have tried the following, although it doesn't work.
var script = '<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>';
document.getElementsByTagName('head')[0].appendChild(script);
</script> closes the opening <script> block, even if it's in a string. I would do it this way:
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//code.jquery.com/jquery-1.9.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script)
})();
You can't have </script> anywhere inside a script block, not even inside a string, because it will end the script block there.
Break up the ending tag in the string:
var script = '<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></scr'+'ipt>';
Just use the jQuery getScript() method to load jQuery: http://api.jquery.com/jQuery.getScript/
...Just kidding.
Try this code:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://code.jquery.com/jquery-1.9.1.min.js';
head.appendChild(script);
From: http://unixpapa.com/js/dyna.html
Also, if using on an https page, you will need to load the script from an https compatible CDN, like the Google Hosted Libraries (src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js")
(function() {
var script = document.createElement('script');
script.type = "text/javascript"; // keeping older browsers happy.
script.src = window.location.protocol + '//code.jquery.com/jquery-1.9.1.min.js';
// browsers prevent cross-protocol downloading.
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);// In Opera a site can get by without a <head>
})();
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.9.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
using a tiny re-usable script adder:
function fetch(url){
var d=document, s='script';
d.getElementsByTagName(s)[0].parentNode.appendChild(d.createElement(s)).src=url;
}
fetch('//code.jquery.com/jquery-1.9.1.min.js');
not all pages have HEADs in all browsers, but if a script is running, so can a sibling script tag...
First of all, the variable script contains the sequence </script> which you can not make it appears as it is in your code, because browser will assume(and it must) that it is <script> tag close.
for example if your script code contains syntax error, which is a string variable that has no close " it will looks like
<script>var bad = "abcd ;</script>
to solve this you can break the </script> string like "</scr" + "ipt>" or you could escape it: "<\/script>"
so:
var script = '<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"><\/script>';
document.getElementsByTagName('head')[0].appendChild(script);
Second thing is that appendChild() function accept a Node element and not a string
so:
var script = document.createElement("script");
script.src = "http://code.jquery.com/jquery-1.9.1.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
Anyway, I prefer to use a module and JavaScript loader like RequireJS.

Javascript to load another js file

I am trying to load another JS file from a JS file.
From my JavaScript file run.js, I have the following:
document.write("<script type='text/javascript' src='my_script.js'></script>");
alert(nImages);
In side my_script.js I have the following:
<SCRIPT language="JavaScript" type="text/javascript">
<!--
nImages = 6;
//-->
</SCRIPT>
But I can't seem to get it to alert the nImages from my_script.js file.
You could do this:
var script = document.createElement('script');
script.src = 'my_script.js';
script.type = 'text/javascript';
script.onload = function () {
alert(nImages);
};
document.getElementsByTagName('head')[0].appendChild(script);
You should not use HTML inside of your script file. Your script file my_script.js should have only this in it.
nImages = 6;
Additional note: you don't need language="JavaScript" or the <!-- or //-->. Those are old conventions not needed for modern browsers (even IE6). I'd also avoid using document.write() in your JS as it has performance implications. You may want to look at a library such as RequireJS which provides a better way to load other JS files in the page.
I also have a code snippet on Github inspired by Steve Souders that loads another file via straight JS.
var theOtherScript = 'http://example.com/js/script.js';
var el = document.createElement('script');
el.async = false;
el.src = theOtherScript;
el.type = 'text/javascript';
(document.getElementsByTagName('HEAD')[0]||document.body).appendChild(el);
This will append the other script to the element (if it exists) or the of the page.
Javascript files should not have HTML in them. They should consist entirely of Javascript code, so my_script.js should contain only:
nImages = 6;
This still won't work because when you write the new script tag into the document it doesn't run immediately. It is guaranteed that run.js finishes running before my_script.js starts, so nImages is undefined when you alert it and then becomes 6 later. You'll see that this works:
document.write("<script type='text/javascript' src='my_script.js'></script>");
function call_on_load(){
alert(nImages);
}
If the contents of my_script.js are:
nImages = 6;
call_on_load();
Edit
Since you said in a comment that you can not edit my_script.js you can do this although it is not nearly as nice a solution:
// Force nImages to be undefined
var undefined;
window.nImages = undefined;
document.write("<script type='text/javascript' src='my_script.js'></script>");
(function is_loaded(cb){
if(typeof window.nImages == 'undefined')
setTimeout(function(){ is_loaded(cb); }, 100);
else
cb();
})(function(){
// This is executed after the script has loaded
alert(nImages);
});
This is not a nice solution, however, since it will continue polling indefinitely if there is an error loading the script.
EDIT
You posted in a comment the file you want to include, which has the <SCRIPT at the top. This file is useless and you can't do anything about it client side. You'd have to write a server side script to load the file as text in which case you can just parse it for the value you want.

Dynamic script hack callback

I have a page that only contains a string and need to read it from a page in a different domain. I have tried to do it via a dynamic script hack (to avoid the security restrictions) and can read that string but cant bring it in a callback to keep working with it in a variable.
My problem is that I need to do it only using javascript.
Here is the code that I am currently using:
index.html:
<html>
<head>
<script type="text/javascript">
function xss_ajax(url) {
var script_id = null;
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
script.setAttribute('id', 'script_id');
script_id = document.getElementById('script_id');
if(script_id){
document.getElementsByTagName('head')[0].removeChild(script_id);
}
document.getElementsByTagName('head')[0].appendChild(script);
}
var url = "http://otherdomain.com/ping.html";
xss_ajax(url);
</script>
</head>
<body>
</body>
</html>
ping.html:
1|1739
Very much thanks and sorry my english.
Your result from ping.html dose not have any variables defined, if you say
made an object like
result = [1,1739];
and in index.html you declared
var result = [];
then you could work with that.

Is it possible to use a variable for a javascript reference

Instead of:
<script src="/scripts/myJsFile.v1.js" type="text/javascript></script>
Have something like
<script src="/scripts/myJsFile." + versionVar + ".js" type="text/javascript></script>
This way when we update the js version files the user won't have to clear their cache.
Not in that way, because you're mixing HTML and JavaScript together. HTML does not have JavaScript variables available.
What you can do, however, is adding the <script> tag dynamically, i.e. through JavaScript. That way, you obviously are able to use variables:
<script>
var versionVar = "1.0";
window.addEventListener('load', function() { // on load
var scriptTag = document.createElement('script'); // create tag
scriptTag.src = "/scripts/myJsFile." + versionVar + ".js" // set src attribute
scriptTag.type = "text/javascript"; //set type attribute
document.getElementsByTagName('head')[0].appendChild(scriptTag); // append to <head>
}, false);
</script>
Check out how Google loads their Analytics. Then maybe try something similar like:
(function() {
var versionVar = 9;
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.src = 'http://www' + '.google-analytics.com/ga' + versionVar + '.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
You can't do this in your HTML file directly. But still you can do this inside an script tag if versopnVar is a JavaScript variable in your window context:
<script type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', '/scripts/myJsFile.' + versionVar + '.js');
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script);
</script>
At the end, it's not a good aproach doing this. Please read this article at a list apart to get informed.
Alternative Style: Working With Alternate Style Sheets
It would probably be better to do something like
<script src="/scripts/myJsFile.js?v1" type="text/javascript></script>
Then, when you make and update:
<script src="/scripts/myJsFile.js?v2" type="text/javascript></script>
Which will cause most browsers to pull the file rather than pull from cache. This means that you won't have separate JS files. But will just be forcing the user to pull the most recent.
Also, if you want it to always pull the file you can, in a similar manner, append a random int.
You cannot do that straight out.
One way is with some server side code.
For example in php:
<?php $version = "1.0"; ?>
<script src="/scripts/myJsFile.<?php echo $version ?>.js" type="text/javascript></script>
Not exactly that way, but you can create a new script node with e.g. document.createElement and add it to the page.
var s = document.createElement("script");
s.src = ...
document.body.appendChild(s);
You can also use the document.write call to do the same...
You'd have to update your page to update the variable. Also, you'd have to update your javascript file name every time you changed it.
You can use a query string to make your JS unique.
<script src="/scripts/myJsFile.js?version=2" type="text/javascript></script>
marshall & I had the same Idea.
Also, you'd have to update your HTML file every time you updated your Javascript file.

Categories

Resources