dynamically add route to script src on an html page - javascript

i want to dynamically add route to script src on an html page.
for example,
<script src="../../../library/vendor/jquery/jquery-3.1.1.min.js"></script>
when i use web server and load this code, not working. maybe it should put web server url prefix. so i want to change below.
<script src="mySite/../../../library/vendor/jquery/jquery-3.1.1.min.js"></script>
or,
other things that root-relative path set?

This cannot be achieved by html or javascript only. You need at least a framework which is able to "render" your html before it is send to your browser and replace "mySite".
Example in JSF 2.x it would look like this:
<link href="#{request.contextPath}/css/style.css" rel="stylesheet" type="text/css"/>
Or Thymeleaf:
<a th:href="#{/order/list}">
If you want to develop for example a one page site, where the content is replaced dynamically by ajax, then you need at least one page which is dynamically created by one of this frameworks.

Use below JavaScript code:
var scr = document.createElement('script');
var myurl = 'http://example.com/myjavascript.js'
scr.setAttribute('src',myurl);
document.head.appendChild(scr);
or you can create a function like this:
function addMyScript(url) {
var scr = document.createElement('script');
scr.setAttribute('src', url);
document.head.appendChild(src);
}
you can dynamically decide your url and call the function by passing it as a parameter:
addMyScript('http://example.com/myjavascript.js');

Related

How to use external html file in current html code

I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});

Javascript ads in Angular templates

I'm trying to render a Javascript ad in my Angular template but it will not show up. I've found some solutions when they append the Javascript to the head tag but I want the ad to be placed in my Html (inside body).
Here is a Plunker: https://plnkr.co/edit/WHhQ95gS5HKSphmmirio
Here is a simple plain Html example that works.
<html>
<head>
</head>
<body>
<div class="ad">
<script src="http://media.affiliatelounge.com/data/nordicbet/ad_js/display_88.js?ad=ad_793270_88.html&size=300x250&clicktag=http://record.affiliatelounge.com/_sVuSoFFh4LK58VwA2IUESrKVVrME-Gsw/1&media=108786&campaign=1"></script>
</div>
</body>
</html>
But if I add the div inside an Angular template it will not render and the console says nothing.
I have some ads up and running here (http://www.odds.nu/erbjudanden), but they are either .gif or iframes. I want to be able to show Javascript ads instead. They are added to the Html but are not rendered (placed in the bottom of the page).
Can $sce or $compile help somehow?
My index.html
<div data-ng-view="" class="mainView"></div>
My app.js
$routeProvider.when("/erbjudanden", {
controller: "offerController",
templateUrl: "/app/templates/offers.html"
});
My offers.html
<div class="ad">
<script src="http://media.affiliatelounge.com/data/nordicbet/ad_js/display_88.js?ad=ad_793270_88.html&size=300x250&clicktag=http://record.affiliatelounge.com/_sVuSoFFh4LK58VwA2IUESrKVVrME-Gsw/1&media=108786&campaign=1"></script>
</div>
Any solution?
If you had inspected result of that url request(make sure adBlock is off)
https://wlbetclic.adsrv.eacdn.com/S.ashx?btag=a_17172b_14837c_&affid=12824&siteid=17172&adid=14837&c=
You will see the actual result
document.write('<script type="text/javascript" src="//wlbetclic.eacdn.com/TrafficOpt/s.5.4.min.js?t=1"></script>');
document.write('<script type="text/javascript" src="//wlbetclic.eacdn.com/wlbetclic/img/js/Affiliate_12824.js?t=20160224"></script>');
//other lines omitted for brevity
So this file is executing document.write which obviously will not work in angular, just because they are totally different (even though you could trigger digest cycle somehow, you still don't have access to modify that script file, as it's generated by 3rd party server and has own variables)
What i would do is - make a page like ad.html, just like index.html or 404.html, then request this file from angular (not as template, but like a view file) as an iframe src with custom attributes
And i would use custom DOM element, and populate contents with jQuery, or with angular, look at jQuery sample below
Also i would need krux/postscribe plugin, because you cannot use document.write in async html files
<!-- create multiple holders -->
<ad-holder url="https://wlbetclic.adsrv.eacdn.com/S.ashx?btag=a_17172b_14837c_&affid=12824&siteid=17172&adid=14837&c="></ad-holder>
<div class="black-widow">
<!-- with size attributes -->
<ad-holder url="http://google.com" width="100" height="40"></ad-holder>
</div>
<!-- jQuery population with iframe -->
<script>
//get all custom elements
$('ad-holder').each(function(){
//create iframe placeholder
var $iframe = $(document.createElement('iframe'));
//get url of custom element
var url = $(this).attr('url');
//request ad.html file with params, currently it's url param
$iframe.attr('src', 'ad.html?url=' + url);
//some stylings acceptable here
$iframe.width('100px');
//or get styles from custom-element
var heightValue = $(this).attr('height');
$iframe.height(heightValue || '50px');
//rebuild custom element with iframe
$(this).append($iframe);
});
</script>
<!-- angular populate with iframe directive -->
<scrip>
angular.module('app', []).directive('adHolder', function(){
return {
restrict: 'E',
scope: { url: '#' },
//you could also execute in compile-phase
link: function(scope, element, attribute){
var $iframe = angular.element(document.createElement('iframe'));
$iframe.attr('src', 'ad.html?url=' + scope.url);
element.html($iframe);
}
}
});
</script>
And ad.html would look like
<body>
<div id="ad"></div>
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
//for the sake of simplicity we expect only 1 param (url)
return query.replace('url=', '');
}
var adUrl = getQueryVariable('url');
if (adUrl)
postscribe('#ad', '<script src="' + adUrl + '"><\/script>');
else {
var $h1 = $(document.createElement('h1'));
$h1.text('No ad available');
$(document.body).append($h1);
}
</script>
</body>
The best part of this solution is that you can reuse same custom-element with different url attribute for any other ads
Checkout jQuery real working demo
Although this demo heavily uses jQuery, it's easy to tweak for angular version, which i would suggest you to implement as homework =)
Short answer:
Angular does not perform compilation of Javascript in HTML templates. You either put the HTML manually in the page (instead of loading as template) or have another way to call it.
You can read more here

How do I load a specific javascript file or javascript code into an HTML document?

Here's what I'm trying to do;
I have this HTML code:
<div id="background-color-random">
DIV CONTENT
</div>
And this javascript:
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
I want to impliment this on an HTML page. I know that you can load up a *.js file by using the script tags with src="..". But that doesn't seem to work.
The javascript creates a random color and then applies that to the background of a given 'div' in the HTML.
Now, I'm not good with javascript, so please be patient with me and simple answers are needed :)
I need to be able to get the javascript to load when requested from the HTML and then apply itself to the div with id="..".
You have a syntax error (missing a comma):
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
Should be
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
You are using jQuery, not pure javascript. That's a good thing...
but you also must add the jQuery library in your head tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
You also need to put semi-colons (or commas, as RobM has corrected me, if between var assignments) at the end of each instruction. See line 3 in your code example.
If you want your js/jQuery code in a separate file, you can load the script code like this (again, usually done in the <head> tags):
<script src="filename.js" type="text/javascript"></script>
Or, you can include the js/jQ in the <head> tags of your document, like this:
<script type="text/javascript">
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
</script>
If including the script as an external file, you leave out the <script></script> wrapper from that file.

Chameleon templates for javascript files?

I am developing a simple pyramid application where I am using JQuery to do AJAX requests. I have until now had my javascript code within my chameleon templates. Now I want to extract my javascript into another location (e.g. as static resources).
My problem is that I find my javascript code relies on dynamically generated content like so:
$.post("${request.route_url('my_view')}",{'data': 'some data'}, function(html){
$("#destination").html(html);
});
The dynamic element being:
"${request.route_url('my_view')}"
Which is calling the route_url method of the request object within the template.
Is there a recognised pattern for separating such javascript files into their own templates and providing routes and views for them or do I simply keep my javascript in my page template?
Yes; you generally put context-specific information like expanded routes into the templates and access this information from your (static) JavaScript libraries.
Including the context info can be done in various ways, depending on taste:
You could use a data attribute on a tag in your generated HTML:
<body data-viewurl="http://www.example.com/route/to/view">
...
</body>
which you then, in your static JS code load with the jQuery .data() function:
var viewurl = $('body').data('viewurl');
Use a made-up LINK tag relationship to include links in the document head:
<head>
<link rel="ajax-datasource" id="viewurl"
href="http://www.example.com/route/to/view" />
...
</head>
which can be retrieved using $('link#viewurl').attr('href'), or $('link[rel=ajax-datasource]').attr('href'). This only really works for URL information.
Generate JS variables straight in your template, to be referenced from your static code:
<head>
...
<script type="text/javascript">
window.contextVariables = {
viewurl = "http://www.example.com/route/to/view",
...
};
</script>
</head>
and these variables are referable directly with contextVariables.viewurl.

How do I switch external CSS files?

I've got a couple books that I'm reading on AJAX, but still quite new. All the tutorials and these books have the ubiquitous examples of: an auto-populating search bar and an asynchronous form validator. Those are both great, but not what I'm looking for. Specifically, I want to click a button and switch the external CSS file in my header include. Is this possible? Well... I know it's possible, but how do you do it?
PS: I have jQuery in this project, so if there is something built in from there, even better!
PPS: I'm realizing I have not included important information (don't shoot me!):
The final goal of this will be to have a user settings section where the user can click a radio button and decide the color scheme they want to use for our app. So we will eventually have something like 8 different CSS styles to choose from. Not sure if this will alter the best method to achieve this.
The user is logging into their account and changing their setting there. I want their changes to 'stick' until they decide to change the stylesheet again. I can do this manually in MySQL as we have a table called stylesheets with the various user stylesheets numbered... so in actuality, what I'm needing to do is change that MySQL value asynchronously so the CSS is immediately loaded.
Add an id attribute to the CSS link tag to manipulate the tag using JavaScript:
<link id="cssfile" href="css/avocado.css" type="text/css" rel="stylesheet">
The Javascript to set the href attribute resembles:
document.getElementById('cssfile').href = 'css/carrot.css';
Colours could be tweaked by the user, by clicking a link:
<a href="#"
onclick="document.getElementById('cssfile').href='css/carrot.css';">Carrots</a>
By changing the media type, this could also allow users to quickly change print layouts, the preferred layout on mobiles (or tablets), and more.
This solution does not require jQuery.
See also: http://www.webmasterworld.com/forum91/4554.htm
Stylesheet Switcher in jQuery.
In response to the 'newbie followup' comment, I will try to make it a little more instructional.
The page I was playing with to test on while writing can be found here.
Page Display
You're going to want to have your current stylesheet displayed in a <link> tag in the <head> of each of your pages. The <link> tag will need an id for reference later in JavaScript. Something like:
<?php
// Somewhere in the server side code, $current_stylesheet is read from the user's
// "preferences" - most likely from a database / session object
$current_stylesheet = $user->stylesheet;
?>
<link href='<?php echo $current_stylesheet ?>' rel='stylesheet' type='text/css' id='stylelink' />
Changing the preference
Once you are displaying the users stylesheet, you need a way to change it. Create a <form> that will send a request to the server when the user changes their stylesheet:
<form method="GET" id="style_form" >
<select name="stylesheet" id="styleswitch">
<option value="css1.css">Black & White</option>
<option value="css2.css" selected="selected">Shades of Grey</option>
</select>
<input value='save' type='submit' />
</form>
Server Side
Now, without jQuery, submitting this form should GET (you could change it to POST if you like) stylesheet={new stylesheet} on the current page. So somewhere in your bootstrap / sitewide include file, you do a check for it, a php sample:
$styles = array(
'css1.css' => 'Black & White',
'css2.css' => 'Shades of Grey',
);
if (!empty($_GET["sytlesheet"]) {
// VALIDATE IT IS A VALID STYLESHEET - VERY IMPORTANT
// $styles is the array of styles:
if (array_key_exists($_GET["stylesheet"], $styles)) {
$user->stylesheet = $_GET["stylesheet"];
$user->save();
}
}
Live Preview
At this point, you have a functioning styleswitcher for the lame people without javascript. Now you can add some jQuery to make this all happen a little more elegantly. You'll want to use the jQuery Form Plugin to make a nice ajaxForm() function, that will handle submitting the form. Add the jQuery and jQuery Form library to the page:
<script type='text/javascript' src='/js/jquery.js'></script>
<script type='text/javascript' src='/js/jquery.form.js'></script>
Now that we have the libraries included -
$(function() {
// When everything has loaded - this function will execute:
$("#style_form").ajaxForm(function() {
// the style form will be submitted using ajax, when it succeeds:
// this function is called:
$("#thediv").text('Now Using: '+$('#styleswitch').val());
});
$("#styleswitch").change(function() {
// When the styleswitch option changes, switch the style's href to preview
$("#stylelink").attr('href', $(this).val());
// We also want to submit the form to the server (will use our ajax)
$(this).closest('form').submit();
});
// now that you have made changing the select option submit the form,
// lets get rid of the submit button
$("#style_form input[type=submit]").remove();
});
Here's an example that uses jQuery.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#change-css').click(function(e){
e.preventDefault();
$('link[rel="stylesheet"]').attr('href', 'style2.css');
});
});
</script>
</head>
<body>
<a id="change-css" href="#">change css</a>
</body>
</html>
The operative line is $('link[rel="stylesheet"]').attr('href', 'style2.css');. This finds any <link> tag that has rel="stylesheet" and changes its href attribute to style2.css.
It has nothing to do with Ajax. It has everything to do with JS and DOM manipulation (Some key words to search for tutorial).
I am using Mootools, which is a JS library and it has a built in function for that.
If doing it manually is your thing, then I would simply add a <link> element to the <head> or adjust the href attribute of an existing <link> element.
<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6063" id='bobo'>
...
...
...
<script>document.getElementById('bobo').href="http://my.doamin.com/new.css";</script>
You could also load both CSS files and preface the all of the selectors on the second file with a body classname.
body.secondsheet {}
body.secondsheet a {}
body.secondsheet hr {}
Then all you have to do is add/remove the "secondsheet" class to the body tag to switch stylesheets.
To add a new css file to a page just create a new <link> tag:
function addCss (url) {
var s = document.createElement('link');
s.rel = 'stylesheet';
s.type = 'text/css';
s.href = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
addCss('http://path/to/stylesheet.css');
To remove a css file from a page just remove the <link> to it:
function removeCss (search) {
var css = document.getElementsByTagName('link');
for (var i=0;i<css.length;i++) {
var c = css[i];
if (c.rel === 'stylesheet' || c.type === 'text/css') {
if (c.href && c.href.match(search)) {
c.parentNode.removeChild(c);
}
}
}
}
// Remove all css that contains 'mycss_', can use regexp if necessary:
removeCss(/mycss_.*\.css/);

Categories

Resources