Inline Javascript is breaking my HTML/CSS - javascript

This is my first attempt to use jquery, javascript and HTML/CSS in one site. I have a working inline script tag that utilizes jquery and javascript. Unfortunately I can't seem to create ANY structure on the page (an h1 title, an aside, moving the rendered javascript anywhere...) while this script is in my index.html. I've done lots of research but there is some fundamental I'm missing here as I can have only one or the other. Can anyone point me in the right direction? Here's a curtailed section:
<body>
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('');
//code code code
}
});
</script>
I've tried putting my html within the body and outside of the script, in the script but outside of the jquery function, and inside the jquery function. How could I get a simple "Hello World" up on this page?

What's happening is that once the page is finished loading, or ready, you are setting the HTML to nothing via $body.html('').
You could try changing it to $body.append('This was generated by jQuery!') and you'll see your hardcoded HTML in addition to some text.

Your Script is a Child of the Body, which inner html you are clearing by asigning an empty String - deleting your inline Script in the process. Have you tried moving your Script to the Head section?

Related

Is it bad to have script tag inside div?

What is bad about having a script tag inside div inside body?
I'm dynamically updating a div to reload a javascript code inside a div. Are there any issues to worry about ?
Edit
As #Bergi insisted on seeing the code. Here it is(see below). This div (along with other div(s) containing presentation HTML elements) are updated via AJAX. This script inside div contains maps to do processing of newly loaded HTML elements on page with raw data.
<div>
<script type="text/javascript">
var namesMap = <dynamic string from server here>;
var addressesMap = <dynamic string from server here>;
</script>
</div>
It is perfectly ok to place the <script> tag anywhere in the body of the document.
From here,
The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.
However, whenever a <script> tag occurs, it pauses the parsing of the code till the script gets loaded, and executed.
You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.
There is not much bad about it. Most widgets work this way. It is still valid HTML.
If you want to embed an AdSense unit in your page, you will need to do it. The same with Amazon widgets. That means majority of websites have a script tag inside div.
There are pros and cons for putting scripts inside html. The good thing is that a small script can be placed close to where it is used so you can more easily understand what the page is doing.
If nobody else but that one location needs that script then it is fine to put it there, I think.
Bad thing is that when you divide parts of your program into multiple locations it becomes more difficult to see and manage how such parts interact and interfere with each other. Whereas if you keep your html and javascript in separate files it becomes easier to understand each independently, and then finally focus on how they interact with each other. What are the "interfaces" between them.
If JavaScript is interspersed into the html then you can not organize your script-code separately from organizing the HTML.
ONE MORE THING to be aware of: If you have a DIV you may think that you can manipulate its content by re-assigning its innerHTML. And that works, except, you can not inject a script into the DIV that way. SEE:
Can scripts be inserted with innerHTML?
So one bad thing about having a script inside a DIV is that you can not replace such a script by re-assigning its innerHTML.
By SCRIPT inside <DIV> still working.
But some annoy with your layout - shacking when scroll.
Best solution: put script inside <body> or <head> :D
It was always a good practice to try to put your <script></script> tags in <head></head>. However, lately arguments appearead whether putting a tags at the end of <body></body> tags, just before made a page more faster.
I would recommend to put your <script></script> in <head></head> section of your HTML document, since it is more preffered. Additionally, putting a <script></script> inside a DIV is not a good practice.
You can post your example for a better answer abour organizing the structure of your document.
To sum up, there is no problem in what you are doing. But a more organized way is what I suggest.

Load pages via AJAX and execute javascript and CSS

I've been searching for a while now, but I can't figure out how to load an entire page via AJAX and still execute all javascript and css.
Mostly I just end up with the plain text without any CSS.
Is there a way to do this? I tried jQuery.get, jQuery.load and jQuery.ajax, but none really work like that.
I have a different solution. You may try it with an iframe. Use jQuery to append an iframe script including all relevant codes into some part of your page (like some div). This may do it for you including CSS, like;
$('<iframe src="your_page.html"/>').appendTo('#your_div');
Or you may try something like;
$('<iframe src="your_page.html"/>').load(function(){
alert('the iframe is done loading');
}).appendTo('#your_div');
I have solved similar problem as following.
Download the webpage over ajax
Iterate it over and find any <script> and </script> tags
Get content from within these tags as text
Create new <script> element and insert there the code
Append the tag to your webpage
Another thing is you will need to somehow call the script..
I have done it this way:
I set standardized function names like initAddedScript callback which I am calling after appending the script to the page. Same as I have deinitScript called when I do not need the code (and its variables,..) anymore.
I must say this is awful solution, which likely means you have bad application architecture so as I have had:)
With css is it the same, but you do not need any handlers. Just append the style tag to your documents head.
If the page you load doesn't have any style data, then the external stylesheets must have relative paths that are not correct relative to the invoking document. Remember, this isn't an iFrame - you aren't framing an external document in your document, you're combining one document into another.
Another problem is that loading your complete page will also load the doctype, html, head, and body tags - which modern browsers will cope with most of the time, but the results are undefined because it's not valid HTML to jam one document into another wholesale. And this brings me to the third reason why it won't work: CSS links outside of the head section aren't valid, and the misplaced head section caused by your haphazard document-in-document collage.
What I'd do for compliance (and correct rendering) is this, which would be implemented in the Success callback:
Copy all link elements to a new jQuery element.
Copy the contents of all script in the head section
Copy the .html() contents from the loaded document's body tag
Append the link elements (copied out in step 1) to your host document's head
Create a new script tag with your copied script contents and stick it in the head too
Done!
Complicated? Kind of, I guess, but if you really want to load an entire page using AJAX it's your only option. It's also going to cause problems with the page's JavaScript no matter what you do, particularly code that's supposed to run during the initial load. There's nothing you can do about this. If it's a problem, you need to either rewrite the source page to be more load-friendly or you could figure out how to make an iFrame suit your needs.
It's also worth considering whether it'd work to just load your external CSS in the host document in the first place.
I suppose you are looking for something like this:
your page div --> load --> www.some-site.com
After a quik search the closest solution seems to be the one by "And": Load website into DIV
You have to run a web server and create a proxy.php page with this content:
Then your JQuery load() function should be like this:
$("#your_div_id").load("proxy.php?url=http://some-site.com");
NB. I have tested this solution and it should not load all the CSS from the target page, probably you'll have to recreate them. For example the image files stored on the remote server will not loaded, I suppose due to authentication policy.
You will be also able to view only the target page without the possibility to browse the target site.
Anyway I hope this could be a step forward to your solution.
Get your entire webpage as text using ajax
document.open();
document.write(this.responseText);
document.close();
OR
document.documentElement.outerHTML = this.responseText;
But you need to change the path of css and js pages in original webpage if the resulting webpage is in another directory.

Is it possible to intercept/handle/parse the HTML inside of the body tags before the browser?

I'm wondering if it is at all possible to take whatever is inside of the tags, run it through Javascript and manipulate it before throwing it back for the browser to then parse.
I'm sure it can be done, however it may not be as straightforward as I am suggesting.
For instance, is there a way for the Javascript to take the entire source code of the HTML file and put it into a var as text?
I don't know if it's possible with straight JS, but a tricky way of achieving the same effect would be to set your body to display:none, then have your JS parse and spit it back out, then set body back to display:block.
The earliest point at which you could actually start thinking about manipulating a page which hasn't finished loading is when the page DOM is loaded. Any attempt to do so before that point is most likely going to result in failure. That's the reason most JavaScript frameworks/libraries have special methods which allow users to invoke their code once DOM is loaded.
EDIT: If you just want to remove certain elements from the page before they are loaded your best bet is to remove them form the page DOM right after the DOM has been loaded which will prevent the browser from even getting the chance to load the unwanted resources. I will give you an example which makes use of jQuery but only because it has a nice method called ready() which is fired right after the DOM has been loaded. That said this is perfectly achievable with plain JavaScript, though a bit more complicated.
$('document').ready(function(){
$('.unwanted-elements').remove(); // You can use any other selector you want.
});
This code will remove the unwanted elements from the DOM tree before the resources which are potentially inside of them are even loaded.
Dump all your BODY HTML into a JS variable from the server end and do the following
<html>
<head>
<script type="text/javascript">
var bodyHTMLStr = "<?=dumpPageBody?>";
//Create a element dynamically and dump 'bodyHTMLStr' as innerHTML to it
var dummyDIV = document.createElement("DIV");
dummyDIV.innerHTML = bodyHTMLStr;
//Now you can all the processing you want. Once done dump dummyDIV html into BODY's innerHTML
</script>
</head>
<body>
</body>
</html>

Javascript document.write weird behaviour in Firefox

When I write the following code directly into my html page under a script tag, the string "test" gets appended to my page without replacing the rest of its content (1):
document.write("test");
However, if I place that same code into a separate javascript file like (2):
<script src="http://127.0.0.1/whatever.js" type="text/javascript"></script>
Suddenly that same code rewrites my entire page.
Is there a way to perform a document.write() from a remote file and get the result in (1)?
Thanks for your time.
If you use doc.write while the page page is rendering, it will insert or append the string. If you use doc.write after it's rendered, or after window.onload, it will essentially begin the rendering process again, and overwrite the page.
It's my guess that you are getting asynchronous behavior when loading the script, and it's not executing until after onload. I can't recreate your problem.
You may be including your script at the top of the page. Where it gets the document.write() stuff and thus writes the text instead of a append behaviour.
The safer solution is to append a document element to the page - that should always work

jQuery append doesn't work fully with <script> tag

Appending a script element using jquery rather than putting it in the html by hand seems to lead to very different results. For instance
snaphtml = '<script src="http:\/\/seadragon.com\/embed\/lxe.js?width=auto&height=400px"><\/script>';
$('#content').append(snaphtml);
destroys the layout of my page, but putting the script element in the page directly works fine.
I have posted a test case online:
Working example with script in html.
Broken example with script appended via jquery.
The second div should not be deleted / invisible once the silverlight object is added.
Ideas?
I would recommend you to use $.getScript method for loading external script files programmatically:
$.getScript('path/to/script.js', function() {
alert('Script loaded.');
});
The script load is made asynchronously, and as you see in the above example, you can specify a callback function that will be executed when your external file has been loaded and is ready to use.
Tristan, you will not be able to include the script you reference dynamically onto the page after it has finished loading. The external script is using document.write which will only work correctly when called before the page has finished loading. This is why your static implementation works fine, and your dynamic one tears the page apart.
You might want to put together a dummy HTML file that just has a basic HTML structure and this script in it already. Then dynamically add an iframe to your page that loads the HTML. There are even more dynamic ways to make it work with an iframe, but that would be the easiest.
Try to use $.getScript:
$.getScript("http://seadragon.com/embed/lxe.js?width=auto&height=400px");
Edit:
The provided script is using document.write, which is likely causing your problems: you cannot add it dynamically at the middle of the page. Try loading SeaDragon as shown here:
http://www.seadragon.com/developer/ajax/getting-started/
try to break script tag like
snaphtml = '</sc'+'ript>'

Categories

Resources