Is there a way to not load html until JavaScript loads? - javascript

I want to make sure that all JavaScript happens before the page is loaded. I am changing some innerhtml, but don't want the original innerhtml to show.
Currently, when my page loads "Books" is displayed for a brief moment, then finally when the script is read, it gets replaced. How do I prevent it from displaying the initial text?
FYI the script exists inside a php file.
<?php
?>
<script>
function changeme(){
var myvar = "test-string-is-long-to-notice-the-changed-text";
var spans = document.getElementsByTagName("span");
for(var i=0;i<spans.length; i++) {
if(spans[i].textContent.trim().toLowerCase()==="books") { //is this the "Welcome" span?
spans[i].innerHTML = myvar; //change to new value
break; //hop out of the loop, we're done
}
}
}
window.onload = function() {
changeme();
};
</script>

It is not a good idea to load JS before HTML, because you can not change the HTML elements before loading it using js.
Solution 1: Initially, keep the html tags empty that you do not want to show, because you want to show new data from JS.
Solution 2: Initially, keep the styles for those elements "display: none" and when you add the data using Js in element. Update the style to display: 'block' or any other you want, eg spans[i].style.display = 'block';.

You cant apply JS to a html document that doesnt yet exist. Your html is always loaded first, then your JS is applied. What you could be seeing here is the html is loaded and the JS is taking like what--a second to load and make the change? I recommend figuring out a more efficient way to implement the JS you need. You could just be seeing JS latency. You could use a more efficient implementation plus some CSS to fix it. I could be wrong here but it just doesn't make sense to apply JS to html went the html isnt even there yet.
How would I apply any JS to that if I'm trying to do it before the browser has even parsed and rendered my html?
Also remember that PHP is always "loaded" first, then html, then JS

Related

How to switch between original DOM and the DOM changed by a Content script?

I'm making a Chrome Extension that changes the DOM of a page. But I would like to give the user an option to switch between the page before the changes and the changed page.
It's a little bit like Google translate where you can change between the orginal language and the translated message.
I could not find anything in my own searches.
I know JavaScript but not JQuery yet.
Thanks for the help.
You could save the entire body in a variable, then start overwriting things. If you want to switch back load up the old body.
You could save all the original DOM content to a variable before running the content script. You can do this by using the following code at the top of your content script:
var originalDOM = document.getElementsByTagName("*");
This saves the entire DOM in an array called originalDOM. The * acts a universal tag, requesting every tag in the document. You can read more about the .getElementsByTagName() API here.
You could try:
var html = document.getElementsByTagName("html")[0];
var page = html.innerHTML;
This will give you everything between the <html> tags.
After the content script is injected, run:
var newPage = html.innerHTML;
Now, whenever you want to switch between the pages, simply run:
html.innerHTML = page; //or newPage
You can read more about the .getElementsByTagName() API here

Can new elements inserted with javascript be seen with view-source?

My code is as follows:
window.onload = initialise;
function initialise() {
var objPForSubmitMsg = document.createElement('p');
objPForSubmitMsg.setAttribute('class', 'submitmsg');
var arObjForms = document.getElementsByTagName('form');
for (i = 0; i < arObjForms.length; i++) {
var objFormParent = arObjForms[i].parentNode;
alert(objFormParent);
objFormParent.insertBefore(objPForSubmitMsg, arObjForms[i]);
}
} // end initialise().
I checked the function with alerts and it goes through.
When I "view-source" for the page after the function initialise() is done, there are no new elements added.
So my first question would be as per subject: can new elements inserted with javascript be seen with view-source?
If yes, then what is wrong with my code above? Why it doesn't insert new element?
I also tried to call initialise() from a button, but nothing happens then either.
I'm new to javascript so any comments would be appreciated.
EDIT: Thanks everyone. Ok, view-source cannot see it...
Than if I pass my page to php and load it with: $page = file_get_contents("mypage.html"); , if I echo that back with: echo $page; then I guess the newly created elements will not appear there either?
If that is the case, how would you pass the whole thing including the newly js created elements to php?
View Source in the browser shows you the original HTML source of the page - exactly what came from the server before any client side modifications have been made.
As such, it will NOT include any dynamic changes to the page made by javascript.
To see changes that have been made dynamically, use a DOM inspector. There is one built into Safari and Chrome and IE and Firebug is an add-on for Firefox. All will show you the entire DOM hierarchy, live exactly like it currently exists in the browser. In fact, you can even modify the live DOM yourself in the inspector.
Your current code is inserting an empty <p> tag which may not be visible because it's empty. If you put some content into the <p> tag, it successfully inserts one <p> tag into your page. It will only insert one because you only create one and then you try to insert the same tag before each form. You can see what your current code does here: http://jsfiddle.net/jfriend00/3fvbj7re/.
If you want a <p> tag inserted before each form in the page, you'd need to create a separate <p> tag for each insertion like this:
function initialise() {
var arObjForms = document.getElementsByTagName('form');
var objPForSubmitMsg;
for (i = 0; i < arObjForms.length; i++) {
objPForSubmitMsg = document.createElement('p');
objPForSubmitMsg.innerHTML = "hello"; // give tag some content
objPForSubmitMsg.setAttribute('class', 'submitmsg');
var objFormParent = arObjForms[i].parentNode;
objFormParent.insertBefore(objPForSubmitMsg, arObjForms[i]);
}
}
window.onload = initialise;
The Dom elements you add at runtime, were not present when the first time your page was loaded. In other words, it wasn't a part of your original page.
When you view source of your original page, it just shows the HTMl, without executing any JS or CSS, since you only explore HTMl in the source.
Hence, even when you add dynamic html elements in a page, you won't be able to see them when you click view source.
To see those elements, you should use the Developer Console of a browser.
If you want to see the current DOM you should use the code inspector (Developer Tools) or javascript console, not the source, which is what the original response body was.
In Chrome for example go to view->developer->developer tools
I would like to add that just because you can't see it with view-source, doesn't mean you can't access your newly created elements using document.getElementById('el-id') or something similar. Kinda off topic but it's important to note.

document.write to display content on same page.

I have a doubt with javascript document.write method. Mostly when I use document.write() it shows me the content written with the method in a different page. For instance, if I write the command like this, document.write("Hello, My name is Sameeksha"); then the execution of this line takes me to a different document on the same page. I want to be able to append the message on the same page, with other elements of the page. For example, if I have text boxes and buttons on the page and I want the text with document.write to appear under all the content of the page or on a particular section of a page. Please suggest what can be done to get the output in this way? As, this way it will be really easy to create dynamic HTML content.
Thank you so much for your time.
Regards,
Sameeksha Kumari
document.write is basically never used in modern Javascript.
Whan you do instead is to create explicit DOM elements and append them to the document in the place you want. For example
var x = document.createElement("div"); // Creates a new <div> node
x.textContent = "Hello, world"; // Sets the text content
document.body.appendChild(x); // Adds to the document
Instead of appending to the end you can also add child nodes to any existing node. For example:
function addChatMessage(msg) {
var chat = document.getElementById("chat"); // finds the container
var x = document.createElement("div");
x.textContent = msg;
chat.appendChild(x);
}
I'd say 6502 posted the more correct way to do it, but I think someone should mention innerHTML as well. First, give some element in your HTML body an id so you can reference it:
<div id="outputDiv">I'm empty.</div>
Then, either at the bottom of your document (at the end of the <body> tag), or any other time after the page is loaded, you can update the contents with innerHTML:
document.getElementById("outputDiv").innerHTML = "<h1>Hello!!!</h1>";
Here's a jsfiddle demonstrating this. This isn't as clean/correct/elegant as using the more standard DOM methods, but it's well supported. Sometimes quick and dirty is what you need!

Javascript If statement to run some html code

I've got a little bit of javascript embedded in my html (using a .aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines.
You don't really "run" an HTML code. HTML is a markup language and it is mostly used to format and arrange elements that are displayed in the web browser.
The problem you are probably trying to solve is: Display or hide an element based on some condition. A JavaScript code like this is what you want.
if (condition) {
document.getElementById('chart').style.display = "none"
} else {
document.getElementById('chart').style.display = ""
}
Of course whatever element is responsible for displaying the chart should have an id="chart" attribute. e.g. <div id="chart"><!-- Chart related code goes here --></div>.
The JavaScript code I have given alters the display CSS property of this element to hide it or make it visible.
In case this is not what you want but you want to dynamically modify the HTML responsible for the chart, then you need to use the innerHTML property of the element.
Example:
if (condition) {
document.getElementById('chart').innerHTML = "<!-- HTML Code for the chart here -->"
} else {
document.getElementById('chart').innerHTML = ""
}
I'm assuming the if statement should be written in javascript
Unless you are testing something that you can only find out out in JS, then do it server side in your ASP.NET code.
I don't really know how to "run" this html code from within
This is covered by chapter 47 of Opera's WSC: Creating and modifying HTML. You may wish to read some of the earlier chapters first.
java
Java has about as much in common with JavaScript as Car does with Carpet. They are completely different programming languages.
Try writing the if statement in javascript and then rendering the html with the JQuery html() function. Just use a custom html id to locate where you want the html code to go.
<div id = "custom-tag"> </div>
<script>
if (true){
$('#custom-tag').html('YourHtmlString');
} else {
$('#custom-tag').html('DifferentHtmlString');
}
</script>
Read more about html() here: http://api.jquery.com/html/
YourHtmlString & DifferentHtmlString is where you should store your custom html in string format. It will then be rendered wherever you included "div id = 'custom-id'
Hope this helps!

jQuery - dynamically remove head elements on click

Does anyone know if you can remove head elements on a button click and how to do it with jQuery?
I am trying to get rid of certain script tags from the html head when a button is clicked.
For instance. I have 1 screen view with a slideshow controlled by an external javascript file. When I click on a button "Click to get rid of this elements JS" I want to remove the external javascript path from the HTML Head.
Any ideas. Have been at this thing for a week or so.
You can add an id to a script element then remove that ID:
<script type="text/javascript" src="init.js" id="initJs" ></script>
<span id="removeScript"></span>
$('#removeScript').click(function() {
$('#initJs').remove();
});
You can do this sort of thing using javascript, sure, but before you do it, you might want to ask yourself again why. Here's a link describing how to do it in pure javascript with a jquery example provided by the other answerer:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
But try to keep in mind that most modern browsers will keep these external resources in memory for at least as long as the page is open. Therefore, you won't really be doing much.
I don't think its a good Idea to remove Entire HEAD Element. 'Cause your Page may contain some more Elements (i.e., title, style..) which are appended to Head Element. If you want to remove a particular script Element do something like
$(function() {
$('input[type=button]').click(function() {
$('script[src=path/file.js]').remove();
});
});
Edit :
var flag = false;
function breakTheCode() {
if(!flag) {
//run your code
}else return;
}
$(function() {
$('input[type=button]').click(function() {
flag = true; //flag is set, so we no more using/ running your code
breakTheCode(); //call you function/method
});
});
For my part the best solution is to use ID on the scripts.
I read many page over the web, try many solutions, and the only one who works fine every time is to remove a script like a div with an id !
For remove js file : $("script[src='your.js']").remove();

Categories