Php includes and js scripts position - javascript

I bought a theme where pages were all HTML with JS scripts loaded at the bottom. I modified the theme and now have PHP files with the following (quite standard, with php includes to load the required content) :
index.php
header.php
menu.php
footer.php
content1.php
content2.php
content3.php
...
All the scripts are still loaded at the end, in footer.php.
My problem lies in the fact that in each content pages I need specific scripts, for exemple content1.php needs script1.js, content2.php needs script2.js...
Here is where I have trouble understanding the proper way of doing it :
I could load all scripts (script1.js, script2,js and script3.js) in the footer therefore whichever content is loaded, the required script will be loaded anyway. But I end up loading scripts that are not being used.
For example, I have a script that generates and displays a table from a json array (which is generated using php and a mysql query). This table is only displayed in content1.php.
I don't want to load this script in the footer as it will then be executed each time a page is displayed even if we don't need it. And I can't include it in content1.php as it requires other scripts (jQuery) which is loaded in the footer, ie. after the php include itself.
Does that make sense ?

Use PHP conditionals (either an if/else or switch, which might be better) to check the URL value and load the appropriate scripts for the page in header.php. Very rough example below.
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'content1') !== FALSE) {
echo '<script src="script1.js"></script>';
}
elseif (strpos($url,'content2') !== FALSE) {
echo '<script src="script2.js"></script>';
}

Why not load the ones you need more often in the header file i.e. jquery and call the optional files at the bottom of the page where they needed, there by removing all calls from the footer

You may be better off combining the files and including the new file in the footer. One file would result in fewer requests, but keep an eye on the file size.

Done a small thing few years ago as follows:
<?php
if(getPageJsname()!='') {
?>
<script type="text/javascript" src="jquery-code-<?php echo getPageJsname(); ?>.js"></script>
<?php
}
?>
function getPageJsname() {
return $scriptname = trim($_SERVER['SCRIPT_NAME'], "/");
}
After this you can rename all the javascript files as follows:
for page content1.php js name will be jquery-code-content1.js
and vice-versa
See if this help with something

Take this out of the footer:
<script></script>
</body>
</html>
And put it in each page accordingly.

in content1.php create a var
$script='script1.js';
the same in content2.php
$script='script2.js';
and content3.php
$script='script3.js';
finally in footer.php
echo '<script src="'.$script.'"></script>';

Well, easiest and obvious solution would be to load jQuery before content blocks start. While it is recommended and good to include scripts at the bottom, it's not that of a cornerstone. It is also recommended to combine and compress your JS, so you can generate one compressed JS for all your pages.
But you can also try to load scripts via AJAX after document is rendered. There is http://api.jquery.com/jQuery.getScript/
And you know what content is loaded by that point.
$(document).ready(function() {
if ($("#content1").length > 0) { ... }
});
You can also try to wrap your code in function to postpone it's execution untill jQuery is also loaded.

Related

Refresh div which includes sprintf

I have two php files. The first is named index.php, the second one is named data.php. I tried to get the contents from the file data.php into index.php. Initially it gave me an error using the include_once statement but I now got it to work with:
<?php $str = sprintf(include_once ("/www/index1.php"));
echo $str; ?>
Now, I want this part to refresh every minute without reloading the complete page.
I tried inserting into index.php the following:
<!-- Div refresh function -->
<script type="text/javascript">
var auto_refresh = setInterval(
(function () {
$("#data").load("/www/data.php"); //Load the content into the div
}), 60000);
</script>
<div id="data"><?php $str = sprintf(include_once ("/www/data.php"));
echo $str; ?></div>
I admit, it looks a bit wrong and guess what, it doesn't work. I this is because it tries to load data.php in de script-part and afterwards I try to include the file again in the < div>-statement. I can't get it to work.
I have looked a various examples but can't find any using the sprintf function. I must admit that my knowledge of java, ajax and or json is not great.
Hope someone can help!
Javascript is a front end script. If you want to load something via ajax, you should know its based on js. While js is based on web browser. So make sure you can access that url from browser first.
You can access /www/data.php from php, but if you want to load it in js, make sure it can be visit from web first. How can you visit your index.php?
If you can visit index.php via http://xx.com/index.php, then change $("#data").load("/www/data.php"); to $("#data").load("http://xx.com/data.php");, you will find it works.
Update: Based on your comment, try $("#data").load("data.php");
Also, you can use developer tools to debug it. If js gets error, you will see it.
You're doing something wrong.
What you need to do:
Create file with needful data (for example data.php).
Create file for loading data-file (for example loader.php). If you are using php (I see you are), you can file_get_contents for data.php and then echo it.
On page, where you want to get your data, use something like this:
JS:
function loadData() {
$("#data-container").load("loader.php", function() {
console.log("Load was performed.");
});
}
loadData(); // load first then refreshing every 1 min:
setInterval(loadData, 60000);
HTML:
<div id="data-container"></div>
So, what all of this doing here?
First, script on your page create request to loader.php;
Second, loader.php executes (I hope your server execute php, huh?) and get content of data.php (so in this context data.php can have any file name extention; data.txt, data.log, etc); then it echo that content;
Third, script on your page get echoed (by loader.php) content of data.php and paste it in your #data-container.
These steps repeat again every 1 min.
Note: If data.php in your context is not a programming code (just some data), you can create just data.html and load it directly in jQuery script. It's not need any php-loader files, etc.

Properly loading scripts and dependencies in correct order using head.js?

I am not sure if I am utilizing head.js correctly. In the header of my html document I call the head.js file via:
<script src="/scripts/head.min.js" type="text/javascript"></script>
Then right before the closing < / body > tag in the html page, I call the following file:
<script src="/scripts/load.js" type="text/javascript"></script>
In the load.js file I have the following code:
head.js(
{livechat: "/scripts/livechat.js"},
{jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"},
{jquerytools: "http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"},
{slider: "/scripts/jquery.nivo.slider.pack.js"},
{prettyphoto: "/scripts/jquery.prettyPhoto.js"},
{sliderfunctions: "/scripts/slidercode.js"},
{functions: "/scripts/functions.js"}
);
Does the above code cause the javascript files to execute in the same exact order they are listed or do they sometimes execute out of order?
I ask because the slider initially only functioned if I utilized the following code within load.js:
head.ready("slider", function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
I was able to get around this by moving the above code to an external file called slidercode.js which contained the following code:
$(window).load(function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
But I am not sure if I am going about this the correct and most efficient way as this is my first time using head.js. Basically from the javascript files in loader.js I need to make sure:
jquery loads first.
Once jquery has fully loaded then jquerytools loads
After jquery is fully loaded, it should load slider first and then prettyphoto.
Then sliderfunctions should load as it is dependent on slider,
Lastly, functions should load as it is dependent on jquery and jquerytools.
You should call the scripts like this: (remove the http as well, it's not needed. Also Jquery always loads first of any scripts. in this case headJS has priority then jquery then all your scripts)
<script src="/scripts/head.min.js" type="text/javascript"></script>
// this loads asyncrounously & in parallel
head.load("//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js", "//cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js", "/scripts/jquery.nivo.slider.pack.js", "/scripts/jquery.prettyPhoto.js", "/scripts/slidercode.js", "/scripts/functions.js");
Then right before the closing < / body > tag in the html page, I call the following file:
<script>
head.ready(function () {
// some callback stuff
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
<script>
Does the above code cause the javascript files to execute in the same
exact order they are listed or do they sometimes execute out of order?
Yea, they load asyn, but execute in order.
I think head.ready("slider", function() {} );should also work even if you place it outside of load.js. Try adding it after load.js script block.

Javascript Document.write Issue

I'm trying to get the lines of code below to help me write "<?php include('like.php'); ?>" on a page only when the visitor isn't using a a mobile device but it doesn't seem to be working. Any ideas on how to get it to work?
<script type="text/javascript">
<!--
if (screen.width > 699 {
document.write("<?php include('like.php'); ?>")
}
//-->
</script>
By the time JavaScript is writing to the document, it's too late - PHP has already sent everything to the browser. Your next best approach would be to make an AJAX call to fetch the content and append it to the DOM.
Assuming you're willing to use a JavaScript framework like jQuery, it's quite simple:
if (screen.width > 699) {
$.ajax({
url : '/like.php',
dataType : 'html',
success : function(data) {
$('#myContainer').html(data);
}
});
}
http://api.jquery.com/jQuery.ajax/
As others have mentioned, you can not have JavaScript include a piece of PHP-code and have it executed. As PHP is run server-side, before the page is served to the client, injecting the code like you suggest would just write <?php include('like.php'); ?> as plain text to the document.
You could however load the content of like.php through Ajax and inject it into the DOM, if a certain criteria is met.
With a library like jQuery, it is quite easy, as it provide a method .load() that let you load content into the DOM like that. You could do it something like this:
// Wait for the DOM to be ready
$(function () {
// Check the width of the screen
if (screen.width > 699) {
// Load the content and add the HTML to an element
$('#id-of-element-to-add-content-to').load('like.php');
}
});
In the above example, the content of like.php will be loaded into the HTML-element with id id-of-element-to-add-content-to, but you could use any selector you like, that match your need. If you want to replace the entire body of the page, your could do $('body').load('like.php'); instead.
More about the available jQuery selectors: http://api.jquery.com/category/selectors/
javascript executes on the browser and php executes on the server so, you need to add an if condition and then include
you could test the user agent server side and append that line if not from a mobile device

Load javascript code after jquery.js has loaded in WordPress site

I have a custom jquery-based slider on homepage of a WordPress site. I'm loading jQuery (jquery.js) and the slider js (jquery.advanced-slider.js) using below code in my functions.php file of my theme.
function my_load_scripts() {
if (!is_admin()) {
wp_enqueue_script("jquery");
if (is_home()) {
wp_enqueue_script('theme-advanced-slider', get_template_directory_uri().'/js/jquery.advanced-slider.js', array('jquery'));
wp_enqueue_script('theme-innerfade', get_template_directory_uri().'/js/innerfade.js', array('jquery'));
}
}
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
Now I put the below code in my header.php file BEFORE wp_head();
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function () {
//Slider init JS
$j(".advanced-slider").advancedSlider({
width: 614,
height: 297,
delay: 1000,
pauseRollOver: true
});
});
</script>
It's obvious here that my jquery.js and jquery.advanced-slider.js load after the JavaScript code above and thus my slider doesn't work. If I put it after wp_head() call in <head> the slider works.
But if I put it after wp_head() wouldn't that be a hack? I want my code to be clean. As twentyeleven theme clearly says
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
I'm very confused here. I might be missing something very simple clue here. But help me out guys. What would be the best way to put the JavaScript before wp_head() and yet have it load after jquery.js and slider.js have loaded?
Add your script block to the bottom of the HTML page, just before the </body>.
Your slider init JS code won't get executed until the full DOM has been parsed in the browser anyway so there is no disadvantage to this.
In fact web performance experts like Steve Souders suggest that script blocks should be added at the end of your HTML page as script blocks block rendering and the page appears to load faster this way.
As per wordpress function reference:
The safe and recommended method of adding JavaScript to a WordPress generated page is by using wp_enqueue_script(). This function includes the script if it hasn't already been included, and safely handles dependencies.
If you want to keep your "code clean" you might rethink how your js is organised.
My approach with wordpress is to (usually) keep a scripts.js for all initialisation and small scripts and separate file(s) for plugins. But everything depends how big and how many files you have - you want to avoid too many http requests and files that are hard to manage.
As well, wp_enqueue_script lets you place the scripts in the footer.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
Wait for loading jQuery with window.onload function, once jQuery file and other js / content loaded then window.onload function will be fire.
<script type="text/javascript">
window.onload = function(){
var $j = jQuery.noConflict();
$j(".advanced-slider").advancedSlider({
width:614,
height:297,
delay:1000,
pauseRollOver:true
});
}
</script>
The code that you are adding to the bottom of the page should be externalized to it's own file and added with the wp_enqueue_script(); function like shown below.
Note the use of the 'true' directive at the end of each call to wp_enqueue_script. That tells WordPress that you want them included at the wp_footer(); hook (instead of the wp_head(); hook) which should appear directly before the closing </body> tag - as per the performance best practices that others have mentioned.
function my_load_scripts() {
if (is_home()) {
wp_enqueue_script('theme-advanced-slider', get_template_directory_uri().'/js/jquery.advanced-slider.js', array('jquery'), true);
wp_enqueue_script('theme-innerfade', get_template_directory_uri().'/js/innerfade.js', array('jquery'), true);
wp_enqueue_script('your-custom-script', get_template_directory_uri().'/js/yourcustomscript.js', array('jquery'), true);
}
}
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
I've removed the jQuery enqueue line you had included because you shouldn't need to register the jQuery script as it's already registered by the WP core and since you have defined it as one of the dependencies it will be included for you.
Since you have wrapped it all in an is_home() conditional statement the all 3 of these files - plus jQuery - will be included in just the homepage.
An easier - but maybe not so nice - hack is to simply add a 1-millisecond timeout
setTimeout(function () {
jQuery('#text-6').insertBefore('#header');
}, 1);
get_template_directory_uri() does give you the theme directory, but this is not what you want if you are using a Child Theme.
get_stylesheet_directory_uri() will give your the directory of your "current theme", so in either case, it is safest to use.

HTML: How to un-include the included .js file on current page

I have an Html file in which i have include a .js file like
<script src="myCode.js"></script>
what can i do to remove that file from according to any condition later?
like:
if(someCondition == true )
{
/* some code to remove myCode.js file */
alert('myCode.js file doesnt exist on this document anymore');
}
Short answer: You can't. JavaScript files loaded like this
<script src="mycode.js"></script>
are executed as soon as the document loads. If it is possible to check the condition during the page load, you could use a document.write() call to include the HTML that loads the script only if the condition is satisfied, or if the script can be loaded after the document has finished loading, you could use something like jQuery's $.getScript().
If it isn't possible either way, the best you can do is to try to undo everything that the script does, such as attempting to remove any functions, DOM elements, timeouts, and event handlers that have been added.
You could rewrite your code so that it looks like this:
if (someCondition != true)
{
document.write('<link type="text/javascript" href="myCode.js" />');
}
That way, you include the .js based on your condition.

Categories

Resources