How do I include javascript files server-side? - javascript

I want to include JS file inside another JS file, on server side, to prevent copy-paste and multiple JS files loading from client.
Just like include('file.js') as PHP would do.

There is no built in way to include other JavaScript files from a JavaScript file ... but you can add them into the DOM ->
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
Example usage :
addJavascript('newExternal.js','body');

As Supercharging javascript article suggest - with PHP you can read all your .js files and create one big js file that you will send in one piece.
This is a simplification of the example from the article, just to get you started:
<?php
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');
$files = array(
'jquery.js',
'myLib.js',
'site.js'
);
header('Content-Type: text/javascript');
foreach (files as $file) {
if (#readfile(SCRIPT_DIR . $file) === false) {
error_log("javascript.php: Error reading file '$file'");
}
}
?>
I would also recommend to read the full article Supercharging JavaScript in PHP to get more info.

JSfile = "1.js, 2.js, 3.js"
for loop it
document.write();

You will have to use a script loader and i would like to recommend script.js by Dustin Diaz who works at Twitter. Project Page on Github.
Here is how you use it
assuming you have a jquery plugin to be loaded in a page here is what you should do
// load jquery and plugin at the same time. name it 'bundle'
$script(['jquery.js', 'my-jquery-plugin.js'], 'bundle')
// load your usage
$script('my-app-that-uses-plugin.js')
/*--- in my-jquery-plugin.js ---*/
$script.ready('bundle', function() {
// jquery & plugin (this file) are both ready
// plugin code...
})
/*--- in my-app-that-uses-plugin.js ---*/
$script.ready('bundle', function() {
// use your plugin :)
})
example is also from project page. Here are steps you should follow
Load the Script.js file first
Now include the dependency loader script that loads all the other wanted scripts async[the content of dependency loader script would be like above]

Related

Path to load a file from Javascript in WordPress site

I'm developping a website using WordPress in which I need to include some data-vis made with javascript. I need to load a file containing data in my JS script. Both the script and the data are located in my theme's folder with the following hierarchy :
theme
--scripts
----my_script.js
--data
----my_data.csv
Say I use d3.js to load the data in my script, using the following code :
d3.csv("path/to/data/my_data.csv", function(error, data){
// Use the data
});
What should path/to/data be ? I'm very confused. Should it be relative to where the script is ? Or to where the page using the script is ? Relative to the server filesystem, or to the site's domain ?
Since I didn't get any answers yet, here's what I ended up doing.
In the page template in which the visualizations are to be displayed, I added the following code to the body :
<script>
var theme_URI = "<?php echo get_stylesheet_directory_uri(); ?>";
</script>
This uses a WordPress function to get the path to the current theme, so getting the correct path to my data files is now trivial :
d3.csv(theme_URI + "/data/my_data.csv", function(error, data){
// Use the data
});

Drupal 7 template views preprocess add javascript: what am I doing wrong?

I have read that the best-practice to add a javascript file to a particular view is to use the preprocessor and drupal_add_js. What I'm trying to add is a Facebook app script. I know the script works, because I've tested just adding it in tags right in the header of the view.
What isn't working for me is the code I've added to my theme's template.php file below. As far as I can tell from searching, this should work (obviously replacing THEME_NAME and VIEW_NAME with the actual names), but the js file is just not being added. I also tried just adding it to every page in my theme's .info file, just to see if it would work adding it to every page, but no luck.
function THEME_NAME_preprocess_views_view(&$vars) {
$view = $vars['view'];
if ($view->name == 'VIEW_NAME') {
drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . '/js/facebook.js');
}
}
Just call preprocess for each view. For help visit this link
function bartik_preprocess_views_view(&$vars) {
$function_name = __FUNCTION__ . '__' . $vars['view']->name;
if (function_exists($function_name)) {
$function_name($vars);
}
}
function bartik_preprocess_views_view__test(&$vars) {
$view = $vars['view'];
if ($view->name == 'test') {
drupal_add_js(drupal_get_path('theme', 'bartik') . '/js/facebook.js');
}
}

PHP Get Rendered Javascript Page

I'm developing application using AngularJS. Everything seems to be nice until I meet something that leads me to headache: SEO.
From many references, I found out that AJAX content crawled and indexed by Google bot or Bing bot 'is not that easy' since the crawlers don't render Javascript.
Currently I need a solution using PHP. I use PHP Slim Framework so my main file is index.php which contains function to echo the content of my index.html. My question is:
Is it possible to make a snapshot of rendered Javascript in HTML?
My strategy is:
If the request query string contains _escaped_fragment_, the application will generate a snapshot and give that snapshot as response instead of the exact file.
Any help would be appreciated. Thanks.
After plenty of times searching and researching, I finally managed to solve my problem by mixing PHP with PhantomJS (version 2.0). I use exec() function in PHP to run phantomJS and create Javascript file to take get the content of the targeted URL. Here are the snippets:
index.php
// Let's assume that you have a bin folder under your root folder directory which contains phantomjs.exe and content.js
$script = __DIR__ ."/bin/content.js";
$target = "http://www.kincir.com"; // target URL
$cmd = __DIR__."/bin/phantomjs.exe $script $target";
exec($cmd, $output);
return implode("", $output);
content.js
var webPage = require('webpage');
var system = require('system');
var page = webPage.create();
var url = system.args[1]; // This will get the second argument from $cmd, in this example, it will be the value of $target on index.php which is "http://www.kincir.com"
page.open(url, function (status) {
page.onLoadFinished = function () { // Make sure to return the content of the page once the page is finish loaded
var content = page.content;
console.log(content);
phantom.exit();
};
});
I recently published a project that gives PHP access to a browser. Get it here: https://github.com/merlinthemagic/MTS. It also relies on PhantomJS.
After downloading and setup you would simply use the following code:
$myUrl = "http://www.example.com";
$windowObj = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);
//now you can either retrive the DOM and parse it, like this:
$domData = $windowObj->getDom();
//this project also lets you manipulate the live page. Click, fill forms, submit etc.

WordPress - Plugin - enqueue image files from WP plugin directory in a JS-file

I'm new with creating plugins for WP and I'm still learning. I have two questions concerning the same issue:
1:
First I included the js-file in my plugins php-file:
function theme_name_scripts() {
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js');
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
It works but what I want to do is to locate it from my plugins url (wordpress/wp-content/plugins/example), not from my template directory. How do I do this?
2:
In my js-file, I need to include some image files from the plugin base url (wordpress/wp-content/plugins/example/pix). This script worked when not used as a plugin:
window.onload=function()
{
/* Example */
bp='/pix/', // base url of my images
imgnum=4, // number of images
thumb1=document.getElementById('thumb1'), // id of changing image
combobox1=document.getElementById('selection1'); // id of combobox.
combobox1.onchange=function()
{
thumb1.src=bp+'imagefile'+this.value+'.png';
}
I understand that bp='/pix/', is wrong. But what is correct? I want to load the images from a folder in template_directory. How do I do this? I have read through these two threads but I cant seem to figure it out:
Wordpress: How can I pick plugins directory in my javascript file?
write php inside javascript alert
You can use plugins_url() to enqueue scripts from the plugin directory.
In your case, it would be something like:
function theme_name_scripts() {
wp_register_script('script-name', plugins_url('js/example.js', __FILE__));
}
To make the plugin url path available in javascript, you can use wp_localize_script() in combination with for example plugin_dir_url() (which you also can use above I guess...).
So the end result would be something like:
function theme_name_scripts() {
// register your script
wp_register_script('script-name', plugins_url('js/example.js', __FILE__));
// or
// wp_register_script('script-name', plugin_dir_url(__FILE__) . 'js/example.js');
// make variables available in javascript
wp_localize_script('script-name', 'wordpress_vars',
array('plugin_path' => plugin_dir_url(__FILE__)));
}
And in your javascript you will have the wordpress_vars variable available. Your plugin path will be wordpress_vars.plugin_path.
Note that I have modified the wp_localize_script to send an array as its 3rd argument.

Scrape web page data generated by javascript

My question is: How to scrape data from this website http://vtis.vn/index.aspx But the data is not shown until you click on for example "Danh sách chậm". I have tried very hard and carefully, when you click on "Danh sách chậm" this is onclick event which triggers some javascript functions one of the js functions is to get the data from the server and insert it to a tag/place holder and at this point you can use something like firefox to examine the data and yes, the data is display to users/viewers on the webpage. So again, how can we scrap this data programmatically?
i wrote a scrapping function but ofcourse it does not get the data i want because the data is not available until i click on the button "Danh sách chậm"
<?php
$Page = file_get_contents('http://vtis.vn/index.aspx');
$dom_document = new DOMDocument();
$dom_document->loadHTML($Page);
$dom_xpath_admin = new DOMXpath($dom_document_admin);
$elements = $dom_xpath->query("*//td[#class='IconMenuColumn']");
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo mb_convert_encoding($node->c14n(), 'iso-8859-1', mb_detect_encoding($content, 'UTF-8', true));
}
}
You need to look at PhantomJS.
From their site:
PhantomJS is a headless WebKit with JavaScript API. It has fast and
native support for various web standards: DOM handling, CSS selector,
JSON, Canvas, and SVG.
Using the API you can script the "browser" to interact with that page and scrape the data you need. You can then do whatever you need with it; including passing it to a PHP script if necessary.
That being said, if at all possible try not to "scrape" the data. If there is an ajax call the page is making, maybe there is an API you can use instead? If not, maybe you can convince them to make one. That would of course be much easier and more maintainable than screen scraping.
First, you need PhantomJS. Suggested install method on Linux:
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
tar xvf phantomjs-2.1.1-linux-x86_64.tar.bz2
cp phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin
Second, you need the php-phantomjs package. Assuming you have installed Composer:
composer require jonnyw/php-phantomjs
Or follow installation documentation here.
Third, Load the package to your script, and instead of file_get_contents, you will load the page via PhantomJS
<?php
require ('vendor/autoload.php');
$client = Client::getInstance();
$client->getEngine()->setPath('/usr/local/bin/phantomjs');
$client = Client::getInstance();
$request = $client->getMessageFactory()->createRequest();
$response = $client->getMessageFactory()->createResponse();
$request->setMethod('GET');
$request->setUrl('https://www.your_page_embeded_ajax_request');
$client->send($request, $response);
if($response->getStatus() === 200) {
echo "Do something here";
}

Categories