So my journey with this issue started when I initially was trying to asynchronously load a reddit social media widget. If you open the URL in the getScript parameter below you'll notice that this does a direct document.write. If I didn't didn't capture that code, it would have rewritten the entire document when I run .getScript.
var content = '';
document.write = function(s) {
content += s;
};
$.getScript('http://www.reddit.com/domain/skattertech.com/new/.embed?limit=4&t=all&sort=new&style=off', function(){
$('body').append(content);
});
The code above works, but despite the default async nature of .getScript, pairing it up with document.write causes my entire JS file to halt from running until it has the data to write. IF reddit's server is slow or doesn't respond, the rest of my other widgets won't load.
Is there any simple workarounds to solve this? Is it possible to fetch that script as a string to then split and pop the document.write wrapper off? If the only thing left is the HTML, I can easy write that in at anytime without affecting the rest of my script right?
Sahas, with your clever trick of overriding the document.write function, I don't see any delay at all in executing the following script:
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
document.write = function(s) {
$("body").append(s);
};
$(function() {
$.getScript('http://www.reddit.com/domain/skattertech.com/new/.embed?limit=4&t=all&sort=new&style=off');
$("#testDiv").fadeIn('slow');
});
</script>
<style type="text/css">
#testDiv
{
background-color: #0c0c0c;
color: #fff;
display: none;
}
</style>
</head>
<body>
<p>This is a test</p>
<div id="testDiv">
<p>This is a test.</p>
<p>This div won't be shown until after $.getScript() executes.</p>
<p>Blah blah blah.</p>
</div>
</body>
I executed it several times and, even if reddit was slow to respond, my
$("#testDiv").fadeIn('slow');
code executed well before reddit was finished sending my page back the script.
Am I missing the problem?
Related
When I am using curl in order to retrieve a html page, I face with the following message:
Please turn JavaScript on and reload the page.
I am not sure how to handle this, hence I can open the same page on my web-browser.
[Q] How could I fix this in order retrieve html-page's information only using terminal?
$ curl http://bsod.pw/
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("recaptcha-form").submit();
}
</script>
</head>
<body>
<div id="recaptcha-loading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; z-index: 30001; opacity: 0.8;">
<p style="position: absolute; color: White; top: 30%; left: 40%;">
<img src="https://250410.selcdn.ru/antiddos/lg.rotating-balls-spinner.gif">
</p>
</div>
<center><noscript><h1 style="text-align:center;color:red;"><strong>Please turn JavaScript on and reload the page.</strong></h1></noscript>
<form id='recaptcha-form' action="/captcha" method="POST">
<button id='submitbutton' style="visibility:hidden;" class="g-recaptcha" data-badge=bottomright data-sitekey="6LcigjgUAAAAACyu9edrmWKmIce8h0kIFQz7iyRo" data-callback='onSubmit'></button>
<script>
window.onload = function(){
document.getElementById('submitbutton').click();
}
</script>
<br/>
</form>
</center>
</body>
</html>
If you do inspect element on the site(http://bsod.pw/) you can see that more detailed html code.
Thank you for your valuable time and help.
There is no "error". You make a GET request using curl. It returns you some HTML. The HTML happens to contain mostly links to JavaScript code that your browser is supposed to load and to execute. Your browser (with JS activated) could load the .js scripts and run them. Those scripts would generate some neat web page. If you don't load the linked scripts, and do not execute them, then you don't get much out of the page. Consider using a proper headless browser instead (see example below).
Here is a small example that is supposed to demonstrate the point:
<!DOCTYPE html>
<html>
<head>
<title>Source code empty, page full!</title>
</head>
<body>
<div id="fillThis">
<p>Almost nothing there in the source code!</p>
<p>... but inspect this div after JS is executed.</p>
</div>
<script>
var fillThis = document.getElementById("fillThis");
for (i = 0; i<1000; i++) {
var child = document.createElement('p');
child.innerHTML = "tons of content " + i;
fillThis.appendChild(child);
}
</script>
</body>
</html>
Just save this as "something.html", and open it in the browser. When you ask you browser to show page source, this is exactly what you will get. However, when you inspect the div by right-clicking on it, it will show a that it has >1000 child elements appended to it. Those are generated by JS in your browser, they do not come from the server in form of HTML.
Edit
I tried to access the page using PhantomJS, it almost worked. Here is what I did:
#!/bin/bash
cat <<HereDoc > /tmp/phantomjsScript.js
var page = require('webpage').create();
page.open('http://example.com', function(status) {
if(status === "success") {
console.log(page.frameContent);
}
phantom.exit();
});
HereDoc
phantomjs /tmp/phantomjsScript.js
This is a bash script that generates a helper script in /tmp, which is then executed by phantomjs. PhantomJS loads the website, and also executes the JavaScript. Unfortunately, the website that you've linked to is protected by a captcha-mechanism, and is not directly accessible, so the above example uses example.com instead. If you can somehow work around the captcha, you probably can use a similar script to load the HTML, run the JS, and then dump the rendered DOM to the console.
Try running the code on chrome. Actually the error is due to captcha connection and the error says "Cannot contact reCAPTCHA. Check your connection and try again."
I've built a webpage that is basically a main-page with a div that is filled with different pages by using AJAX. This basically works by loading pages into a div by using innerHTML. One problem I ran into was when a page with javascript is loaded into that div all of the other code runs fine; just the javascript doesnt work.
Main-page(index.php):
<html>
<head>
<script type="text/java">
////bunch of functions////
////Ends up that page_request on this instance is 'graph.php'////
document.getElementById('mydiv').innerHTML=page_request.responseText
</script>
</head>
<body>
<div id="mydiv"><div>
</body>
</html>
Child-page(loaded in div(graph.php)):
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" media="screen" />
<script src="other_stuff.js"></script>
</head>
<body>
<script>
///bunch of script////
</script>
</body>
</html>
Now when loading the page itself (opening graph.php) I notice that everything works fine; it is just when I import graph.php to index.php through innerHTML into my div it does not work (no errors just nothing is shown). I have read through many other posts and guides and did not come up with any distictive solution; thinks I have seen were:
Put eval() around my code [I saw on a guide that this could lead
to malicious user attacks].
Create the scripts on the main page then just import the data using:
document.createElement() and .parentNode.insertBefore()
Create a listener and call the functions when I open graph.php
And this good example
Even though I am not 100% sure how this example could work because I have php populate information for the javascript to collect and then make my graph on graph.php; so if I put that function into index.php the php will already be loaded so I would have to refresh the page or call them to update information somehow. Just for some context I am ok at php but I am new and struggle with javascript so I do not know what solution would fit my situation or work the best. Any tips/examples would be greatly appreciated, thank you for your time.
From you code snippets it seems you're looking to embed complete pages within the main page. If that's the case, a more straightforward approach would be to use an iframe element instead.
For example:
...
<div id="main-page-container">
<iframe src="some-path/graph.php" scrolling="no" frameborder="no"></iframe>
</div>
...
See reference and usage example.
I would suggest using jQuery's .load() function for this.
Take a look here: jQuery API
Older browsers such as IE8 and below don't allow you insert a string that contains javascript and execute it, in any form.
Take for instance:
function addScriptText(js_code) {
var element = document.createElement("script");
element.innerHTML = js_code;
document.head.appendChild(element);
}
will not work in IE8 and below.
You must use eval to accomplish this:
function addScriptText(js_code) {
window.eval.call(window, js_code);
}
Otherwise you need to dynamically request an external js file such as:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "externalScript.js";
document.getElementsByTagName("head")[0].appendChild(script);
Note: The page you are loading (page2.html in this example) must be on the same domain as the page that is loading it (page1.html in this example)
Working solution with jQuery:
Page 1:
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#page2").load("page2.html");
});
</script>
</head>
<body>
<h1>Page 1 Header</h1>
<div id="page2">
</div>
</body>
</html>
Page 2:
<h2>Page 2 Header</h2>
<script type="text/javascript">
alert("Page 2 loaded and javascript executed!");
</script>
When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.
any suggestions as to why this is?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="program.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
with external javascript
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
VERSUS
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
</script>
</body>
</html>
I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom ready event and it should work, Assuming your path to the external javascript file is correct.
$(function(){
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
});
Always use firebug (console) to see what is wrong with the script, if you run into any script errors.
Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.
Wrap your js code in external file in
$(document).ready(function(){
//your code goes here
});
Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme') and $("p") are empty set. In the second example you run this code after rendering html with that elements.
The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...
Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.
Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.
Though rather than just moving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.
Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).
To sum up here's some example code:
<html>
<head></head>
<body>
<!-- all your markup here -->
<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>
<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
//wrap in document ready to be extra safe
$(function() { /*code here*/ });
</script>
</html>
It is possible not to show html page in user browser until some JavaScript(built-in or in separate file) will be loaded and executed(for page DOM manipulation)?
The easiest thing to do is to set the css variable
display: none;
to the whole page.
then when everything is loaded you can set the display to
display: block; // or something else that suits.
If you make sure that piece of CSS is loaded at the very start of your document it will be active before any html is shown.
if you use a javascript library like jQuery you'll have access to the $(document).ready() function, and can implement a switch over like this:
<html>
<head>
<title>test</title>
<style type="text/css">
body > div {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('body > div').css('display', 'block');
});
</head>
<body>
<div>
This will initially be hidden.
</div>
</body>
</html>
Not in the classical way you'd distribute a page. Browsers will (usually) start to display chunks of the base HTML file as it arrives.
Of course, you could simulate this by generating all the HTML on the fly from some included Javascript file. But that doesn't sound like a good plan as it will degrade horribly for people without JS enabled, or if you have a minor bug in your script. A better option might be to style the body tag to display: none and restyle it from the script to make certain parts visible again.
What is it you're actually trying to achieve? It sounds like there's likely to be a better way to do this...
Place the content of HTML page in a DIV, make its diplay none and on load of body diplay it.
<script type="text/javascript">
function showContent() {
var divBody=document.getElementById('divBody');
divBody.style.display= 'block';
}
</script>
<body onload="showContent()">
<div id="divBody" style="display: none;">
<--HTML of the page-->
</div>
</body>
Examples of what you might want to do:
Facebook's "BigPipe": http://www.facebook.com/notes/facebook-engineering/bigpipe-pipelining-web-pages-for-high-performance/389414033919
This method allows you to load JS first then ASYNC+inject all DOM content.
GMail
Zimbra (open-source web app similar to MS Outlook/Exchange)
My understanding is that you want to run some javascript code before you load the page. In the js file you write your init function and add the eventlistener to the window on "load" event. This will ensure that the init code gets executed first and then you can start displaying the HTML content.
var Yourdomain = {};
YourDomain.initPage = function(){
/* Your init code goes here*/
}
window.addEventListener("load", YourDomain.initPage, false);
All You really need to do is give your element an ID or CLASS and use the dislay: none; property. When your ready to show it just delete it.
CSS:
#div_1 {
display: none;
}
HTML:
<div id="div_1">
<p>This will be the hidden DIV element until you choose to display it.</p>
<p id="js_1"></p>
<script>
var x = "Some Test ";
var y = "Javascript";
document.getElementById("js_1").innerHTML = x + y;
</script>
</div>
Users in my site are seeing a half-second glitch on each page before any jQuery code executes. This code manipulates the page so you can visibly see elements move in one big chunk, making the user experience feel clunky. I'd prefer the page not to display at all until the JavaScript has run.
I'm using jQuery provided by the Google API in a page as follows:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript" src="MyScript.js"></script>
In MyScript.js:
google.setOnLoadCallback(runOnLoad);
function runOnLoad() {
// Do stuff
}
Does anyone know if it's possible to run the JavaScript before the page is displayed in the browser?
You could probably add a css class to your main div that would hide the content, and then remove that class as the last thing that MyScript.js does.
In your html template:
<body>
<div id="mainContent" class="hidden">
</div>
</body>
The css class:
.hidden
{
display: none;
}
Last executed statement of MyScript.js:
$("#mainContent").removeClass("hidden");
I would agree with Jan.
Most (not all) browsers load CSS first before javascripts.
So CSS would be advisable for you.