I have seen code like this:
<script type="text/javascript" src="js/my_js.js?id=<?php echo time(); ?>"></script>
I do not understand the reason for the id, nor how to use the id in the .js file, if this is possible.
Thanks.
It is to force the browser to refresh the JavaScript file, otherwise the browser may display a cached version at a later date.
You can also do this to CSS files.
Related
I would like to use js code, which works with php variables.
My situation now:
mainFile.php
<?
$myPHPvar = 1234;
?>
<html>
<body>
MY CONTENT
<script>
var myJSvar = <? echo $myPHPvar; ?>
</script>
<script src="myFile.js"></script>
</body>
</html>
myFile.js
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
console.log(myJSvar);
This works ! But I would like to change this structure. I would like to move the myJSvar definition out from main file into the jsFile.
But If I move this line var myJSvar = <? echo $myPHPvar; ?> into the myFile.js it will not work, because this is not an php file.
Not I thought that this could be a solution:
I rename the myFile.js to myFile.php and change the code like this:
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
<script>
var myJSvar = <? echo $myPHPvar; ?>
console.log(myJSvar);
</script>
and in the mainFile.php I changed <script src="myFile.js"></script> to include('myFile.php');
This works !
BUT:
First question of all: Is this a good idea to do it like this?
Second: The "problem" now: All my files are now php files, also the files, which includes mainly js code. That's not very beautiful, because now I can't see on the first view, which is an js file and which is a php file.
Thank you for your support !
Using PHP, echo the values to hidden HTML fields on the page.
When you know the page is done loading, read them back out using JavaScript.
Note, Ideally, you'd just make the data a separate AJAX/xhr/fetch call to a URL (JSON or XML formatted data is nice for this), but as a stop-gap, hidden fields will do the trick for basic PHP pages.
Similarly, you can echo some inline JavaScript (tags and all) and reference the variables elsewhere. This approach will work but is often referred to as "spaghetti code" because the intertwined front-end (JavaScript) and back-end (PHP) code makes for tricky debugging and does not scale well to larger code projects... months or years after, developers will find themselves scratching their heads as to where code lives, how it's generated, where new code should be placed, etc.
You can do it like this. And there's nothing really wrong with it. You have to bring the data to the client browser somehow. You can do this with: 1. set php variables in the DOM 2. XHR call or 3. cookies
This can be achieved by generating the JS file dynamically... You can create a PHP file that would generate the JS dynamically like:
Note: THIS METHOD IS HIGHLY NOT RECOMMENDED. THIS IS FOR YOUR INFORMATION AND KNOWLEDGE ONLY.
myFile.php (The JS equivalent file)
console.log(123)
Your HTML file
<script type="text/javascript" src="a.php"></script>
But this is highly not recommended because JS files are static resources that can be cached. Using this method would request the JS file every time the page loads (where it will only be transferred at first load only if its static).
The best method is to keep the dynamic variables in your HTML and then include your static JS files which will use these variables.
I want other web sites to link to js file from my domain, like this:
<script language="javascript" src="http://mySite/jsfile.js"></script>
To avoid the cache problem then I need to add a version parameter to the JS file.
But if the version parameter is static then they have to keep updating the link with every new version, so I need a "CHANGEABLE" parameter like this:
<script language="javascript" src="http://mySite/jsfile.js?new Date().getTime()"></script>
How to do that?
in other way: HOW TO MAKE THEM ALWAYS GET THE LATEST VERSION OF MY JS FILE WITHOUT THE NEED TO RE-UPDATE THE JS URL IN THEIR PAGES.
Thanks in advance for your help :)
You can write your <script> tag with js:
<script language="javascript" src="http://mySite/jsfile.js?new Date().getTime()"></script>
with:
<script>
document.write("<script language="javascript" src="http://mySite/jsfile.js?k=" + Date.now() + "'><\/script>");
</script>
this way its posible to add some number or timesamp after your jsfile.
I would make a script, which call my api. Get the lastest js script code, And include it on site,
this way, it's doesn't matter if it's cached the url for the script.
First, Make a .js file, which use Jquery getScript to get and execute. the script you won't have cached .
get the people to use this. then whenever the site is loaded, it get's a new version of the script from your server.
Jobs done.
Im not providing anycode, since, it's more or less using the Jquery getscript. and the docs for that, is better then any sample i could make.
I am just wondering if it's possible to use external JS file that contains PHP code.
my external JS
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
my view page
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot.
You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers)
While this may seems a good and easy way there is many reason not to do this.
Caching (your generated script will not be cached, this may be changed but require additional work)
Memory consumption (every request to this generated js file will require php)
You can simply changed to something like this to get it done (in a better way, IMO):
<script type="text/javascript">
var Settings = {
base_url: '<?= base_url() ?>',
search_city: '<?= $_SESSION['search_city'] ?>'
}
</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
Than content of your js became something like this:
$(document).ready(function(){
// I assume that not using search_city in your sample code
// and some syntax errors, is just by mistake...
$('#update').click(function(){
var tableVal={search_city:Settings.search_city};
$.post(Settings.base_url+'/project_detail/pub',
{'tableVal':tableVal},
function(message){
console.log(message);
})
})
})
quite a common thing to want to do, just rename your js file to "external.js.php" (i use that method, but as long as it ends in php it doesn't matter what you use really) then just change the src url in your script tags and away you go.
Dont forget you may need to include function and config files into the javascript for that base_url() function to work.
Unless you need php for a lot of things in your js file, I'd suggest you don't do as mentioned above and not rename your js file to php to have it parsed. JS files are best served as static.
One thing you can do is have a script at the top of your php document where you assign your base_url variable as a global to be used by all your js:
In your page, before including any js
<script type="text/javascript">var base_url = "<?= base_url();?>";</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
In your js file
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post(base_url+'/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
I believe it is possible, but as Brian mentioned you have to let the preprocessor know it needs to process it. You can either tell it to use php to handle .js files (Not recommended) or simply use a .php file for your javascript, then use:
<script type="text/javascript" src="<?= base_url();?>js/external.php"></script>
This should be okay because the mime type is still javascript so it will be interpreted that way. I've never actually tried this, so it is a guess, but I believe it should work.
Just a quick idea, that could help some people:
I think (never tried) there is also a way to ask the web server (Apache, etc) to let JS files be handled as PHP content.
Advantages:
No need to rename your JS files to .js.php
Takes advantage of caching
Can be applied only to a specific folder (not to every JS file of your website)
Withdraws:
Do not forget that those "php" files are "cached" somewhere, so don't rely on the fact that files are generated every time.
Server resources: as said in other answers, make sure to use such a trick only when it's really not possible to put PHP code outside of the JS files (using ajax queries for instance), or on files that don't load the server too much.
I am using code-igniter, and some of my views require jquery. Because they must be used in multiple places they must call jquery in their file, however since they are referencing an external file, calls to $(document.ready) are evaluated before loading jquery and therefore fail. Is it possible to put jquery in the body and still have it load before an javascript is evaluated. Or alternatively, is the some way to pass the fact that jquery is required back through code-igniter into the headers, which were callled before the file in question.
In a view:
echo $this->import->js('jquery.js','jquery');
echo '<script type="text/javascript">
$(document).ready(function(){$(\'div#login.rounded\').corner();})
</script>';
You can view the page at: http://formulator.codingproject.net/content/login/
NOTE This page actually resides on my home machine, so it is expected that the recaptcha fails.
I guess the answer is yes. you can load the jQuery.js in your body. But you have to write your script tags only after jQuery.js declaration, if not you may end up with errors :)
PS : please correct me If I'm wrong :)
jQuery should really be called in the head element. Here's how you'd do that conditionally (untested).
In your controller, each function that needs jQuery should have:
$data['need_jquery'] = true;
$this->load->view('header');
In your header view:
<head>
<? if($need_jquery) { ?>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" /></script>
<? } ?>
</head>
It looks like you are using PHP? If so, create a static method that returns that string, but only if it hasn't already been included this request. Then you can ensure that it's only being included once.
My website is the same way. What I do is I have one header that is loaded on all pages. In that header I do if($this->uri->segment(2) == 'controller'). Then I load jQuery and certain scripts if needed for that controller.
I think it will be fine if jQuery will be included in the tag of every page, besides, you can use the minified version of jQuery which is not so heavy.
Uh, maybe I'm wrong. But when I view your source code and follow where the jquery file is: http://www.formulator.com/assets/scripts/jquery/jquery.js I get a "page cannot be found" error. So I'm guessing this could be the problem. Maybe the way your php outputs it isn't including the correct domain/subdomain?
i am making a "static" php website in this style
<?php include "header.php" ?>
<?php include "left.php" ?>
<?php include "photos.php" ?>
In "photos.php" i have 3 heavy javascript files from the lightbox and i thought it could be a good to include the javascript files only in this "photos.php" and not at the "header.php".
But javascript supposed to be only in the head html tags. Do you have any better approach or mine is just fine?
thanks very much
It's best to have all javascript in the head whenever you can. And you can without much difficulty. As Dominic Rodger said, it's probably not a big deal to include the js files on every page because they should be cached.
I tend to create page template class files with lots of variables for this sort of thing. A simpler thing to do that's more inline with what you're already doing is to set a variable before you include the header file, then access that variable in the header file and add the js if appropriate.
<?php
$includePhotoJavascript = true;
include "header.php";
?>
In the header file:
if(isset($includePhotoJavascript) and $includePhotoJavascript == true)
{
// add the javascript
}
JavaScript does not only have to be in the head HTML tag. It is actually advisable to put it at the end of the HTML file, because they halt the rest of the HTML file from loading.
What you could do in the header.php file, is something like this:
<html>
<head>
<title><?php print $title; ?></title>
<?php
foreach($javascript as $src){
?>
<script type="text/javascript" src="<?php print $src; ?>"></script>
<?php
}
?>
</head>
Then the file you posted would look like this:
<?php
$title = "Photo album";
$javascript = array("jsfile1.js", "file2.js");
include "header.php"
include "left.php"
include "photos.php"
?>
If you're going down this route, you could try setting a variable before you include header.php which stores whether or not those JavaScript files are needed. It might not be necessary to sweat it too much though, if users tend to stick around on your website they'll fetch those files once and then not again, since hopefully your server will return a 304 Not-Modified response, and they'll be served from your browser's cache.
thanks very much for your ideas.
i am planning of making the home page(index.php) as light as posible. So
i will load javascript(lightbox.js) only in photos.php and try to do a
LAZY LOADING to this lightbox.js so when "first time" visitor go to
photos.php javascript file will be in cache.
and all these in background.
I think is the same Facebook does. Look here
Optimizing Facebook