Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)
Related
I tried like this
<script type="text/javascript" src="myfile.js"?+Date.now()></script>
In browser it is showing as it is.
I want to add some timestamp to each js files.
i.e.,
<script type="text/javascript" src="myfile.js"?+5671836294></script>
Thanks in advance.
You can't randomly stick JavaScript anywhere you like in HTML.
When you are in the middle of an HTML start tag you can either:
End the tag with >
Write an attribute
JavaScript does not belong there.
If you want to generate an HTML attribute value dynamically when the element is created, then you must create the entire element with JavaScript.
e.g.
<script>
var s = document.createElement("script");
s.src = "myfile.js"?+Date.now();
document.head.appendChild(s);
</script>
… but you'd probably be better of solving this problem by properly configuring your HTTP headers for the script instead.
Refresh the page or rewrite the script tag and append it to the bottom of the body.
But once a page is loaded, it is loaded. You have to redeclare to overwrite.
I am trying to include a readmore script in a website.
I tested the script on http://jsfiddle.net/4zL67z6k/ and got a good result for the code.
I have <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> on the first line of the header for my site and I have tested a simple welcome script.
I am not sure why I can't get the read more script to function. Any solutions?
Your this is the p you have clicked on. And you are searching within this p fore .more-content. But the .more-content is outside this p. So just define a container and let the click handler execute on this container.
Try it with next() and not with find().
Is it safe to assume that the last script element* in the document when the script runs** is the currently running script?
For example, I want to create a script that can be dropped anywhere in the body of of a page and display an element in the same place. I'm doing something like this:
function getCurrentScriptElement() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
}
var script = getCurrentScriptElement();
var view = document.createElement('span');
/* Put stuff in our view... */
script.parentNode.insertBefore(view, script);
Assuming the script is in the body of the document, is this "safe?" Will the getCurrentScriptElement function always return the running script? If not, how can it be done?
I'd like to do this without tying the script to a specific id attribute or similar, I'd like it to just be positional.
I created an example here that pulls in this script. One answer suggested that other scripts could create a condition where an example like this would break. Is it possible to add other scripts to this example that will break it?
It was suggested that other scripts with defer or async attributes could break this. Can anyone give an example of how such a script might work?
As I understand it, defer means load the DOM first, and then run the script with the defer tag. How would the defer attribute appearing on another script element affect the behavior of getCurrentScriptElement?
async, as I understand it, means start fetching that script and keep parsing the DOM at the same time, don't wait... but when it hits my script it should still stop and wait, right?
I don't see how either one could affect it, can anyone provide an example?
* I'm only interested in external scripts for the purpose of this question.
** Not the last script element in the entire document, but the last script element in the document at the time when it runs. The rest of the document shouldn't be loaded yet, right?
It's not an absolute guarantee no. Check out this JSFiddle: http://jsfiddle.net/jAsek/
<!DOCTYPE html>
<title>Test case</title>
<div>
<p>At the start</p>
<script id="first">
var scr1 = document.createElement("script");
scr1.setAttribute("id", "early");
document.body.appendChild(scr1);
</script>
<p>After the first script</p>
<script id="second">
function getCurrentScriptElement() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
}
alert(getCurrentScriptElement().id);
</script>
<p>At the end</p>
</div>
Here the alert reports the id of the injected script "early", not the id of currently running script "second".
There's no practical difference between internal and external scripts.
I don’t think it’s a safe assumption at all, as browsers execute javascript code quite differently depending on a number of things (like if you have other script elements in the head, if they are external etc.).
You should just require people to use a dummy element with a custom id or class. That way you will also make it possible to do whatever you do multiple times a page without having to run the script multiple times.
This is also what is done when using widgets, for example Google’s +1 button.
An alternative would be to use document.write to write additional content while the script is executed. This will not replace the script tag however, but simply add something after it.
You probably want to use document.currentScript that is currently supported by 90% of browsers and fallback to document.scripts[document.scripts.length-1] if you're targetting IE
function writeHere(element)
{
var sc = document.currentScript || document.scripts[document.scripts.length-1] ;
sc.parentNode.insertBefore(element, sc);
// or in jquery $(sc).before($(element));
}
note: I didn't test document.scripts[document.scripts.length-1] thoroughly but it should work in most cases (but not in Alohci exemple).
And this is a fix for IE so who cares :)
I am trying to show some JS code in a textarea. The code is generated with JS so I am injecting it into the textarea with JS. However, using the <script> tags, causes the script to execute. I thought using < would solve this, but this is simply displaying < instead of <.
Any suggestions how I can do this?
$('myTextarea').set('value', '<script>alert('do something');</script>');
Just separate the script tag into two.
$('myTextarea').val('<script>alert("do something");</scr'+'ipt>');
The next </script> after the opening <script> block closes the script block; whether it's contained with a JS string or not.
To fix you can either split the </script> like so;
$('myTextarea').set('value', '<script>alert('do something');</scr' + 'ipt>');
Or like this (less common, but works, and probably more correct);
$('myTextarea').set('value', '<script>alert('do something');<\/script>');
Furthermore, you also need to fix your quotes;
$('myTextarea').set('value', '<script>alert(\'do something\');<\/script>');
You can see this now working here: http://jsfiddle.net/pK9SK/
I'm extremely new to coding and I'm reading a book on it. And I think I have the basics down on this little test project I'm doing, but whenever I test the page I just see the code I used. Here's the entirety of my code.
<script type = "text/javascript">;
//<![CDATA[
// from concat.html
var person = "" ;
person = prompt( "What is your name?") ;
alert("Hi there, ") + person + "!");
//]]>
</script>
Honestly I don't know what the CDATA is for or what concat.html is.
How can I get Firefox to run my JavaScript rather than just show the code?
Try wrapping it in <html> to make the whole page get treated as HTML. Does the file have a .js extention, by any chance?
CDATA is to distinguish code from markup.
Put it in an HTML file.
So, first, save it as scriptname.html - you're embedding JavaScript within an HTML file.
Next, make it valid html - add <html> to the top and </html> to the bottom. And <head> and <body> tags where appropriate - if you don't know what those are, head over to any HTML site to look them up (www.diveintohtml5.org is nice, if you can follow it.)
Better install Firebug plugin for Firefox or use other browser's Javascript console. It will allow you to run your code
http://www.w3resource.com/web-development-tools/execute-JavaScript-on-the-fly-with-Firebug.php