As i understand javascript .js files are best to put all the way at the bottom of html pages, to speed up loading of rest of page. Advised by Yslow(Yahoo) and Page Speed(google).
Now, when in the middle of page some thing RUNS a javascript script, in Internet Explorer, i see a small warning message saying that the element is: Uncaught ReferenceError: SWFObject is not defined
When i put my all.js file in the had, the error goes away but page load slows doen. What to do?
Actually, i remember it was the same with php variables. If i RUN php but the variable comes later, then it just doesnt work. must define the variable first, for it to run.
How to make this workflow better, in case of php scripts? and in case of javsscripts?
Thanks!
You should put your library scripts that are external in the head (things like swfobject, jquery, etc.). But the actual function call you make (for example to bind an event with jquery, or to initialize a swfobject embed) should go at the end.
This made even esier if you keep calling global functions outside of an event handler to a minium and dont use inline javascript or global variables.
What is that "some thing" that runs javascript in the middle of the page?
We do not use <script> tags, and all javascript code we put is js files, which are loaded in strict sequences (so I definitely know that when code is executed, everything it uses is there). (ok, to speed up page loading we append all files into few, like probably you do, "all.js")
If you use script in html attributes (like onchange events etc.) then try to use unobtrussive javascript (attach your events from javascript files).
If that does not help, then divide your javascript into few parts - minimum needed to load the page and execute some stuff before other part is loaded (in <head> of page). Bigger part of scripts you will load before </body>
Related
Conceptually, this seems like it should be pretty simple, but I keep finding myself in a catch-22 whenever I try to implement it. (Also, for a variety of reasons, I'd really like to handle this without jQuery or AJAX, if possible.)
On the client side, onload triggers a video to play and a picture to appear. Then, each time the user presses the space bar, a different video plays, until a certain point at which the spacebar triggers the next page to load.
On the server side, PHP arrays control which videos and pictures will be displayed (both the order within a page, as well as which set of videos, out of a total of 70 sets).
Currently, all the client-side action is controlled by a set of JS functions that are included in my html header. All the PHP functions are listed toward the bottom of my main page script. The kicker, though, is that the JS functions necessarily contain some PHP references. For example:
document.getElementById("ImagePort").innerHTML="<img src=Pictures/<? echo $_SESSION['TrialArray'][4] . ">"; ?>";
The issue here isn't the syntax; it's the information flow sequence. The problem is that when these PHP calls are in the header, they appear before the browser makes it to the part where I call the PHP function that assigns values to them. PHP then throws error messages that muck up the JS parsing.
So then the intuitive solution is to either move these JS functions lower down (to a footer, perhaps) or else call the PHP functions before the header loads. However, moving them to the footer didn't solve the problem for me. I sortof thought it would... am I mistaken in that expectation, or have I perhaps made a simple mistake somewhere?
Moving the calls such that they precede the JS function definitions is equally problematic, since then the script doesn't know what the JS functions are called, either by PHP or in HTML.
PHP example: playVid(source) is a JS function, $Instructions is a PHP variable.
if ($_SESSION['Page'] == 0) {
echo "<script>playVid(" . "'" . $Instructions . "'" . ");</script>";
}
HTML example: both setFocus() and ShowFirstStimulus() are JS functions.
<body onload="setFocus(); ShowFirstStimulus()">
Both of these throw an "Uncaught Reference Error: [function] not defined. Again, I'm trying to figure out whether that's because I simply can't do it this way, or if I've just made a mistake in how I've set it up.
Assuming that there really is no way out of this Catch-22 (where PHP functions can't be called before JS functions, and JS functions can't be called before PHP functions), it seems that one remaining option is to simply write some dummy code in which I initialize some PHP variables to some value that's bogus but parse-able. This seems like terrible coding hygiene, but at this point I'm not seeing many other options. Any suggestions?
Please also let me know if I need to clarify anything. Thanks!
between this
<script src="js/script.js"></script>
and that
<?php
echo '<script>';
include 'js/script.js';
echo '</script>';
?>
Which is better?
I'm actually wondering about things like HTTP Request and others stuffs...
(the same goes for CSS styles, should I put everything in the same file and send to the user, thus reducing the amount of requests, or should I properly separate just like everyone else do? thus increasing the number of requests)
There is something else that I should be concerned about?
Ok, it took me second to figure out what you were asking. In your first choice you are outputing a script tag that links to your javascript, in the second you using PHP to include your javascript inline.
Of the two choices, the first is by far the best. Assuming your page content is dynamic, due to browser caching, for every page a person downloads from you, the same javascript will be included everytime. If your javascript is 100kb in size, every page is now an extra 100kb. Over time this will add up for both your server and your clients.
Including your Javascript (and CSS) by linkages allows the browser to cache pages, and only fetch what is necessary. This will similarly reduce the number of requests as a browser will only fetch what is necessary, which in most cases is just the HTML page.
edit: What if the script is used on only one page?
Still include the Javascript by a link, rather than inline. If you page is 100% static, but has thats not one page but many. And each request will get a new output, with the same replicated Javascript. Even if your page is pure-static HTML, still include it by a link as you never know when you might want to reuse the Javascript (or CSS) code.
I would consider something like this
<script src="js/js.php"></script>
where js.php includes all the need js files I assume this will resolve the caching issue, plus you can make things dynamic by adding get values I guess.
btw I find it better to use the php open and close tags for html whenever possible
<script src="<?php echo $var ?>" ></script>
As I commented before, <script src="js/script.js"></script>.
This is in you <head> and it will be implemented before anything goes into you <body>
Since you are building your front end via JavaScript, php functionality will come after everything was built by JS.
Well according to me using the later approach is better , if you are designing a php page it is always better to write everything in php , whereas HTML side scripting is better done inside echo"" or print""; functions , you can read a lot about it in w3schools.com , hope my answer solved your problem.
I have a small script that pulls HTML from another site using Javascript.
I want to include that static HTML that gets pulled in a PHP page without any of the Javascript code appearing in the final PHP page that gets displayed.
I tried doing an include of the file with the Javascript code in the PHP page, but it just included the actual Javascript and not the results of the Javascript.
So how would I go about doing this?
You would need to fetch the page, execute the JavaScript in it, then extract the data you wanted from the generated DOM.
The usual approach to this is to use a web automation tool such as Selenium.
You simply can't.
You need to understand that PHP and Javascript operate on different places, PHP on the server and Javascript on the client.
Your only solution is to change the way all this is done and use "file_get_contents(url)" from PHP to get the same content your javascript used to get. This way, there is no javascript anymore and you can still pre-process your page with distant content.
You wouldn't be able to do this directly from within PHP, since you'd need to run Javascript code.
I'd suggest passing the URL (and any required actions such as click event, etc) to a headless browser such as Phantom or Zombie, and capturing the DOM from it once the JS engine has done it's work.
You could also use a real browser, but of course you don't need a UI in your case, and it might actually get in the way of what you're trying to do, so a headless browser might be better.
This sort of thing would normally be used for automated testing of a site (ie Functional Testing).
There is a PHP tool named Mink which can run these sorts of scripts from within a PHP program. It is aimed at writing test scripts, but I would imagine you could use it for your purposes.
Hope that helps.
I currently am using PHP to render a dynamic JS+CSS+HTML website via echo statements. The PHP is filling in some of the JS variables.
I want to expand this to include If/Else statements but I have some questions about how PHP interacts with the rendered page
After the site is rendered (all the echo statements have printed) can I still call additional PHP functions? For instance, if I click something can I have that call a PHP function?
Feel free to point me toward PHP tutorials that explain how PHP interacts with the site. Ironically I have done a lot of PHP coding for other tasks I just never thought about it from the ground up
PHP does not interact with the site. PHP's only function is to output text to the browser.
Look at it this way: if you had no PHP, the website would be composed of HTML pages. HTML pages can contain JavaScript and the user can interact with them. The difference with PHP though is that you can generate these HTML pages dynamically (which by association means that you can also generate the JavaScript contained in the HTML pages dynamically). Nothing else has changed.
Basically once the PHP script has finished running and printed (echoed) all the html content to the browswer then it stops running.
Essentially if you are clicking on a web page then that can either call a new page via a form POST or a GET OR maybe javascript can handle the click. And then that Javascript can perhaps perhaps trigger a new request. And that new request can call a PHP script which performs whatever task you want it to.
So if you click on an <a href='action1.php?param1=yes'>Click here</a> link then that will call the script action1.php (with $_REQUEST['param1'] set to 'yes') on the webserver and the webbrowser displays anything it returns. And that new html replaces all the html currently in your browser window.
OR if you have a form:
<form action='action2.php' method='POST'>
<input type='text' name='stuff'>
<input type='submit>
</form>
And you click on submit then again the webserver will be called but this time the script action2.php will be called with $_POST['stuff'] set to whatever is in the text field. And whatever the script returns will be what is displayed in the browser.
Now if you want to click on something in the browser and just change something small on the page or just perform some action on the server then you should probably investigate AJAX handlers and jQuery in particular
Good Luck.
I've learned in coding to never say never....
Aside from standard Ajax, there --IS-- a way to run PHP functions asychronously: xajax In a nutshell, it allows you to call PHP functions directly without reloading the page. A word of warning-- the documentation is weak....
PHP is server side technology as others have mentioned. Getting it to run asynchronously (or after the main page has rended, as the case may be) is only facilitated with some Javascript voodoo, which is what xajax brings to the table. It does a "good enough" job making this possible. I personally have chosen to use Jquery because of the sheer power it brings for UI development. There's tons of options out there to make Ajax calls.
The key to moving your understanding forward is thinking about coding for the FRONT END. When I was beginning my career I was solely a back-end guy, focusing on the standard if/thens/elses and echoing out the relevant code. Once it was on the screen, I was done with it. Moving over to concentrate on the front end requires understanding of the dom structure -- what you'll be using to "grab" elements and then understanding of tech such as javascript to "do stuff" with your data. In a nutshell, it's just a different way of doing what you're used to with a slightly different syntax. Rather than just jumping in feet first to tackle Ajax or this specific task, take some time to familiarize yourself with the basics of traversing the Dom, and perhaps some Javascript or Jquery basics as well. It'll make your job much easier in the long run.
Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.
Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:
<body onload="function();">
It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?
Thanks
You have may have mixed up which part does what.
PHP generates the HTML page on the server side. When the HTML page arrives at the browser, PHP has done its job. There is no way for PHP to do something after it has rendered the HTML.
Javascript is executed in the user's browser after the page has been generated and loaded. (Or during; as theraccoonbear points out, Javasript can run in the browser before the page has loaded completely.)
A Javascript command can not communicate with the PHP script rendering the page, because when Javascript comes into play, PHP is already gone.
So the answer to your question is: No, the JS function can not execute before PHP is done. As several commentators point out, that is not entirely true. A Javascript could come into action before the input HTML elements have been rendered. In your example however, the Javascript triggers only when the document is completely loaded. In that constellation, the answer is no, it can't happen.
That shouldn't be an issue, as you are using the body's onload property, which will ensure the dom and all images etc have loaded.
Using jQuery to it like below would be better in my opinion, fires as soon as the dom is ready, rather than waiting for all images etc.
$(document).ready(function() {
// do stuff here
});
This is also easily done from an external JS file if required, which helps you logically separate your code.