Passing a variable value to a variable in a script function (Javascript) - javascript

I would like to know how to pass the value of a variable in JavaScript file to a variable in a script function which is written on top of the HTML file.
I wrote it like this:
myjsfile.js:
var abc = "10";
HTML file:
<html>
<head>
<script type="text/javascript">
(function() {
var test = document.createElement('script'); test.type = 'text/javascript'; test.async = true;
test.src = 'testquery.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(test, s);
alert(abc);
})();
</script>
</head>
<body>
</body>
</html>
I am not getting the output. Please help! Thanks in advance.
Basically I am trying to create a jquery plugin just like Google analytics.

The script has to load first, try using onload
test.onload=function(){alert(abc);}

<html>
<head>
<script type="text/javascript" src="testquery.js"></script>
<script type="text/javascript">
alert(abc);
</script>
</head>
<body></body>
</html>

try this:
(function() {
var test = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(test);
test.type = 'text/javascript';
test.src = 'testquery.js';
test.onload = function () {
alert(abc);
}
})();​
well.. the onload has already been told but you should at least switch your way of appending it to the head.

Related

Function not working if src is a variable?

With this HTML the function myFunc() can be executed. https://myurl.de/myjs.js has the function myFunc in it.
<head>
<script type="text/javascript" src="https://myurl.de/myjs.js"></script>
<body>
<script type="text/javascript">
myFunc();
</script>
</body>
</head>
But with the second HTML I get an Error: Uncaught ReferenceError: myFunc is not defined.
https://myurl.de/settingsFile.js is a file that includes this url in a var: https://myurl.de/myjs.js so basically SettingsFile.UrlToMyJS is this https://myurl.de/myjs.js
<head>
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript" id="myid"></script>
</head>
<body>
<script type="text/javascript">
document.getElementById('myid').src = SettingsFile.UrlToMyJS;
myFunc();
</script>
</body>
When I console.log(document.getElementById('myid')) this is the output:
<script type="text/javascript" id="myid" src="https://myurl.de/myjs.js></script> which is correct. It looks exactly like the script in the head of the first html (with the difference that it has the id="myid").
Yet it does not work. Why and how can I fix it?
settingsFile.js:
var defaultURL = 'https://myurl.de/';
var SettingsFile = {
UrlToMyJS : defaultURL + 'myjs.js',
}
The reason it's not working is that you can't add a src to a script element that's already in the DOM — or rather, doing so doesn't do anything. The script element has already been processed.
Instead, create it and then append it:
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
That waits for the script to load, then calls myFunc (which should exist by then).
Also note that as I and Jeremy pointed out in the comments, body doesn't go in head, it goes after. It's also generally best to put script tags at the end of body (if you're not using async or defer attributes on them or type="module"). So in all, something like:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
Another option is to use document.write. This sort of thing may be the last at-least-partially appropriate use of document.write during the main parsing of the page:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
document.write('<script src="' + SettingsFile.UrlToMyJS + '"><\/script>');
</script>
<script>
myFunc();
</script>
</body>
You can try creating a element and then appending it to your title
For Example (script code) :
var script = document.createElement("script");
script.src = "YOUR_SCRIPT_SRC_HERE";
document.getElementsByTagName('head')[0].appendChild(script);
Here I am creating a new tag in html and then appending it to the head of your html. Even as T.J. Crowder mentioned in the comment try removing your body from the head

Indirect way to insert javascript into an html page

I encountered the following script in a webpage source :
<script type="text/javascript">
WebFontConfig = {"typekit":{"id":"cmr1bul"}};
(function() {
var wf = document.createElement('script');
wf.src = 'https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
From what I see, this script inserts the content of https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js
before the first script in the page. What is the difference between the above and putting
<script type="text/javascript" src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js"> </script>
as the first script in the page ? What is gained by using the longer version ?
It's absolutely equivalent to the following code if both script elements are added before any other one:
<script>WebFontConfig = {"typekit":{"id":"cmr1bul"}};</script>
<script src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js" async></script>
...or:
<script src="https://s1.wp.com/wp-content/plugins/custom-fonts/js/webfont.js" async></script>
<script>WebFontConfig = {"typekit":{"id":"cmr1bul"}};</script>
...because the script is asynchronously included...

insert dynamically string containing script into HTML and executing it dynamically

I have a variable of the form :
var x = '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'
and I want to insert it with jquery into my HTML code and execute it.
I tried using the append, html and eval without any luck.
Any ideas?
sample script:
<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<img src="http://..." width="120" height="600" border="0" alt="">
</noscript>
this will in the end show an img, which will load asynchronously.
Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.
Here is a working fiddle:
https://jsfiddle.net/2vrfxrse/
Javascript
var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);
HTML
<script>executeTest();</script>
This solution will probably work for your specific scenario:
var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);
while (res) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(res[1]));
document.body.appendChild(s);
res = rx.exec(x);
}
JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output
You can use Jquery getScript:
//Moment example
if (typeof moment == "undefined") {
var url = "~/assets/js/moment.js";
$.getScript(url);
}
Or Jquery Function:
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Extracting the first url parameter and then put it inside the script tag

I am working with HTML and Javascript. I am trying to extract the first URL parameter and put it in variable1 variable in my script tag.
Below is my code
<html>
<head>
<title>Applying</title>
</head>
<body>
<script type="text/javascript"
urlId="420"
dataTitle= variable1;
dataemail="admin#domain.net">
</script>
</body>
</html>
And I am not sure how to extract the first parameter from the URL and put it in my variable1 variable in my script tag.
Suppose if the url is like this-
test.html?parameter1=hello
then variable1 variable in my script tag should have hello value after extraction. Any idea how this can be done? Any help will be appreciated.
Updated Code That I have tried
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
</script>
<script type="text/javascript"
urlId="420"
dataTitle= variable1;
dataemail="admin#domain.net">
</script>
</body>
</html>
Will the above code do the required thing that I am looking for?
Create the script element dynamically:
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
The whole solution:
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
</body>
</html>

how can you determine location of <script> tag from inside said tag?

I am trying to figure out the location of the script tag the current javascript is running in. What is really going on is that I need to determine from inside a src'd, dynamically inserted javascript file where it is located in the DOM. These are dynamically generated tags; code snippet:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>where am i?</title>
<script type="text/javascript" charset="utf-8">
function byId(id) {
return document.getElementById(id);
}
function create_script(el, code) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = code;
el.appendChild(script);
}
</script>
</head>
<body>
<div id="find_me_please"></div>
<script>
create_script(byId("find_me_please"), "alert('where is this code located?');");
</script>
</body>
</html>
You could give the script an id tag, like this dude does...
You can use document.write to create a dummy DOM object and use parentNode to escape out. For example:
<script>
(function(r) {
document.write('<span id="'+r+'"></span>');
window.setTimeout(function() {
var here_i_am = document.getElementById(r).parentNode;
... continue processing here ...
});
})('id_' + (Math.random()+'').replace('.','_'));
</script>
This assumes you don't actually have control of the <script> tag itself, such as when it's inside a <script src="where_am_i.js"></script> - if you do have control of the <script> tag, simply put an ID on it, as in:
<script id="here_i_am">...</script>
If you are just running this on page load, this works
<script>
var allScripts = document.getElementsByTagName('script');
var thisScript = allScripts[allScripts.length];
alert(thisScript);
</script>

Categories