How to add script before body element - javascript

It seems to be very simple, but I can understand where I miss the thing:
var string1 = document.createElement('script');
$(string1).attr('type', 'text/javascript');
$('body').before($(string1));
In jquery 2.0.3 version, it works perfect, but I need it works in 1.8.3 version. Where am I wrong ? Thanks

The call to
$('body').before($(string1));
Should actually be
$('body').prepend($(string1));
This will add the script as child of the body, before all other elements.
If instead with before you mean, not in the body, then it should be
$('head').append($(string1));
In fact as #Quentin says in the comments, script tags cannot go directly in html tag.
Also please see the docs for both prepend and before as they have a completely different meaning.

It makes no sense to add a script before the body element. That would lead to invalid HTML.
You should probably add it to the head instead.
$('head').append(string1);
Note: You should really be careful when naming your variables. string1 is misleading as it does not reference a string but a script element.

Related

Can't append script element to head

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)

JS Regexp: get the inline javascripts from html

I need to get all script tags from an html string, separated the inline scripts and the "linked" scripts. By inline scripts I mean script tags without the src attribute.
Here is how I get the "linked scripts":
<script(.)+src=(.)+(/>|</script>)
so, having <script followed by one or more any character, followed by src=, followed by /> or </script>.
This works as expected.
Now I want to get all the script tags without the src tag, having some javascript code between <script .....> and </script>, but I can't figure it out how to do that. I just started understanding regular expressions, so the help of a more experienced r.e. guru is needed :)
UPDATE
Ok, so dear downvoters. I have the html code for a whole html page in a variable. I want to extract script tags from it. How to do it, using jquery for example?
var dom = $(html);
console.log(html.find('script');
will not work. So, what is the way to accomplish that?
UPDATE 2
I don't need to solve this problem with regex, but because now I am learning about them, I thought I will try it. I am opened for any other solution.
Create a DOM element using document.createElement, then set its innerHTML to the contents of your HTML string. This will automatically parse your HTML using the browser's built-in parser and fill your newly-created element with children.
dummyDoc = document.createElement("html");
dummyDoc.innerHTML = "<body><script>alert('foo');</script></body>"; // or myInput.value
var dom = $(dummyDoc);
var scripts = dom.find('script');
(I only use jQuery because you do so in your question. This is certainly also possible without jQuery.)
If you are in the position where no dom access is available (nodejs?), you'd be forced to use regex. Here is a solution that worked for me in the similar circumstances:
function scrapeInlineScripts(sHtml) {
var a = sHtml.split(/<script[^>]*>/).join('</script>').split('</script>'),
s = '';
for (var n=1; n<a.length; n+=2) {
s += a[n];
}
return s;
}

using javascript to output html

I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.
alert("beginning");
//var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
//$('body').append(link);
//document.write("hi");
//document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("before function");
(function(){
alert("middle");
var links = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(links);
alert("after middle");
//alert($("img").attr("id"));
document.write("hi");
document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("end");
}());
I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.
Also, is this the correct way for jquery?
Thanks in advance!
Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.
You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :
$(document).ready(function(){
/* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
or the shorthand version that does same thing:
$(function(){
/*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.
There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here: http://docs.jquery.com/How_jQuery_Works
Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.
It is unnecessary to wrap your html in a JQuery object (in this case):
var links = "<a href='http://juixe.com'>Hello, <b>World</b>!</a>";
$('body').append(links);
or simply:
$('body').append("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:
$("body").html("/*Your HTML here*/")
At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.

how can I get the value of width with javascript

I put this on the head section
var d = parseInt(document.getElementById('test').style.width);
alert(d);
But the output is NaN.
how do you get the value?
UDPATED
I think the problem is that you've put the code in the <head> of your document, which means it's looking for the test element right away. Unfortunately, the test element hasn't been created yet, because your browser is still parsing the <head>.
So, make sure that code is placed after the test element, and use either .offsetWidth or .clientWidth, and it should work fine.
UPDATED
Reading your question, it seems that you are executing the code in your head section before the DOM has loaded, try to put your script in the bottom of your page, just before </body>.
document.getElementById('test').clientWidth;
document.getElementById('test').offsetWidth;
style.width will most probably only get the inline style, you have three options:
You can use .clientWidth , .offsetWidth or you can add a inline-style.
See my example : http://jsfiddle.net/WaSKP/2/
Just use,
window.onload=function(){
alert(document.getElementById("test").clientWidth)
}
That should do the trick.

How do I add a pre tag inside a code tag with jQuery?

I'm trying to use jQuery to format code blocks, specifically to add a <pre> tag inside the <code> tag:
$(document).ready(function() {
$("code").wrapInner("<pre></pre>");
});
Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert
alert($("code").html());
I see that IE has inserted some additional text into the pre tag:
<PRE jQuery1218834632572="null">
If I reload the page, the number following jQuery changes.
If I use wrap() instead of wrapInner(), to wrap the <pre> outside the <code> tag, both IE and Firefox handle it correctly. But shouldn't <pre> work inside <code> as well?
I'd prefer to use wrapInner() because I can then add a CSS class to the <pre> tag to handle all formatting, but if I use wrap(), I have to put page formatting CSS in the <pre> tag and text/font formatting in the <code> tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.
Has anyone else encountered this? Am I missing something?
That's the difference between block and inline elements. pre is a block level element. It's not legal to put it inside a code tag, which can only contain inline content.
Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen.
Could you instead replace the code element with the pre? (Because of the block/inline issue, technically that should only work if the elements are inside an element with "flow" content, but the browsers might do what you want anyway.)
Why is it a code element in the first place, if you want pre's behavior?
You could also give the code element pre's whitespace preserving power with the CSS white-space: pre, but apparently IE 6 only honors that in Strict Mode.
Btw I don't know if it is related but pre tags inside code tags will not validate in strict mode.
Are you using the latest jQuery ?
What if you try
$("code").wrapInner(document.createElement("pre"));
Is it any better or do you get the same result ?
As markpasc stated, a PRE element inside CODE element is not allowed in HTML. The best solution is to change your HTML code to use <pre><code> (which means a preformatted block that contains code) directly in your HTML for code blocks.
You could use html() to wrap it:
$('code').each(function(i,e)
{
var self = $(e);
self.html('<pre>' + self.html() + '</pre>');
});
As mentioned above, you'd be better off changing your html. But this solution should work.

Categories