consider the following code -->
<template id="foo">
<script type="text/javascript">
console.log("00000000");
</script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
</template>
now on appending this to the DOM
var template = document.getElementById('foo')
var clone = document.importNode(template.content,true);
document.appendChild(clone);
gives this output in console -->
00000000
11111111
22222222
Uncaught ReferenceError: $ is not defined
So the question in general is -->
How to properly load into DOM, an html <template> that has
an external script (like jQuery in this case), followed by an inline script having some dependency on it.
Also - this does not happen if template tag is removed -->
<script type="text/javascript">
console.log("00000000");
</script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
How in the latter case, does the browser download it synchronously?
Is it possible to have blocking script download (line by line) in the former case (with template) ?
The problem is that the script is loaded async. That means that it start to load the script from the web, but continues running the code below. So in that case it will execute code below without having loaded jQuery yet.
You only need to load it once, so you could do it at the start, and only once:
var template = document.getElementById('foo')
var clone = document.importNode(template.content,true);
document.body.appendChild(clone);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="foo">
<script type="text/javascript">
console.log(00000000);
</script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
</template>
Another option would be to make sure code below is only executed once the file is loaded:
var template = document.getElementById('foo')
var clone = document.importNode(template.content, true);
document.body.appendChild(clone);
<template id="foo">
<script type="text/javascript">
console.log(00000000);
</script>
<script type="text/javascript">
function scriptOnload() {
console.log(11111111);
console.log(22222222);
var xyz = $;
console.log(33333333);
}
</script>
<script onload="scriptOnload()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</template>
Here's how I handle it in my application (with jQuery):
//Load the template from an external file and append it to the HEAD of the document
$.get("/path/to/your_external_template_file.html", function (html_string) {
$('head', top.document).append(
new DOMParser().parseFromString(html_string, 'text/html').querySelector('template')
);
}, 'html');
//Locate the template after you've imported it
var $template = $("#top_template_element_id");
//If you want to reuse the content, be sure to clone the node.
var content = $template.prop('content').cloneNode(true);
//Add a copy of the template to desired container on the page
var $container = $('#target_container_id').append(content);
Related
How would I be able to pull the data from the JS script within my HTML? I am wanting to pull the "Title", "Description", and "Link" objects and display them within my HTML code.
Here is the code:
<div class="roadMap" id="roadMap"></div>
<script src="/siteassets/bootstrap3/js/jquery-1.8.3.min.js"></script>
<script src="/publiccdnlib/PnP-JS-Core/pnp.min.js"></script>
<script type="text/javascript" src="/publiccdnlib/es6-Promise/es6-promise.auto.js"></script>
<script type="text/javascript" src="/publiccdnlib/fetch/fetch.min.js"></script>
<script src="/publiccdnlib/slick/slick.min.js"></script>
<script src="/publiccdnlib/CommonJS/CommonJS.js"></script>
<script src="/publiccdnlib/knockout/knockout.js"></script>
<script src="/publiccdnlib/knockout/knockout.simpleGrid.3.0.js"></script>
<script src="/publiccdnlib/toastr/toastr.min.js"></script>
<script src="/publiccdnlib/dialog/open-sp-dialog.js"></script>
<!--END Scripts for O365-->
<script>
$pnp.setup({
baseUrl: "https://fh126cloud.sharepoint.com/TrainingResourceCenter/O365Training"
});
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.get().then(function(z) {
console.log(z);
var result = z.results.map(a => ({
Title: `${a.Title}`,
Description: `${a.Description}`,
Link: `${a.Link}`
}))
console.log(result);
document.getElementById("roadMap").innerHTML = JSON.stringify(result, null, 2)
})
</script>
<html lang="en">
<body>
<div>
/* Code goes here */
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
I see you are using jQuery so I will answer relative to it.
Using jQuery you can put text wherever you want using the text method.
For example, if you want to put the Title data in your div you could do:
$("div").text(result.Title);
The code above will place result.Title in every div on the page (which you only have one of.).
There are so many jQuery methods you could use as-well, such as append, prepend, and html. Append will put the text after the existing content of an element. Prepend puts the text before existing content of an element. Html with replace the html inside of an element.
So if you wanted to construct the HTML elements then place them on the DOM (the web page) you could do:
$(document).ready(function(){
var head = '<h1>${result.Title}</h1>';
var desc = '<p>${result.Description}</p>';
var link = '<a src="${result.Link}">${result.Link}</a>';
$("div").html(head + desc + link);
});
To put your Title, Description, and Link on the DOM. Hope this help you, good luck!
I'm trying to handle translations with Mustache.js and it works fine for some part of the code but not for another part.
<script>
function MyFunction() {
// If a submit button is pressed, do some stuff and run this function to display the result
var tmpText = "";
tmpText = "<b>{{someTextInJSfunction}}</b>"; // this is NOT OK
document.getElementById("totalText").innerHTML = tmpText;
}
</script>
</head>
<body>
<div id="sampleArea">
</div>
<script id="personTpl" type="text/template">
<span id="totalText"></span></p>
<b>{{ImpNotice}}</b> {{Contact}} // this is OK
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/mustache.js"></script>
<script>
$( document ).ready(function() {
var lang = 'en_us';
$.getJSON('json/'+lang+'.json', function(data) {
var template = $('#personTpl').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
});
</script>
When I click a Submit button, my JS function is called and depending on some calculation, some text should be displayed in the page. This is the part that doesn't work, {{someTextInJSfunction}} is displayed instead of the actual content of {{someTextInJSfunction}}.
The content of {{ImpNotice}} and {{Contact}} is correctly displayed because I assume the variables are located in the <script id="personTpl"> tags.
I'm not sure how to fix it for the variables located in my JS functions, such as {{someTextInJSfunction}}.
Ok, I have this code:
<script language="javascript">
window.onload = function(){
var s = document.createElement('script');
s.src = 'jscript.js';
document.getElementsByTagName('body')[0].appendChild(s);
} </script>
<script type="text/javascript" src="https://www.facebook.com/dragosgaftoneanu"
onload = "alert('logged in')"
onerror="alert('not logged in)">
</script>
I want to execute the code from the first script at the onload of the second script. I have jscript.js where it is defined function().
as what i understand, do you want to call the first js file using the second js file?
here is the code
in your file2.html you need to add the src of the first file
<script language="javascript" src='location'></script>
<script language="javascript">
function init()
{
name();//call the function name. It's either in this file or in your first file
}
</script>
<body onload="init()">
I'd like to load and execute an external javascript file (Google Adwords's conversion script) only if a condition is met. Similar questions have already been asked, I've tried their solutions but it didn't work. I've the following code :
<script>
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js');
}
});
</script>
The script is loaded but isn't executed. How do I do to execute it ?
I've tried to change getScript() with
var script = document.createElement("script" );
script.setAttribute("src", "//www.googleadservices.com/pagead/conversion.js" );
document.getElementsByTagName("head" )[0].appendChild(script);
but it didn't work as well.
Thanks !
#VLAS: Oops pasted the wrong thing, corrected
#ejay_francisco: I already tried to create the script tag and append it to the head but it doesn't work
#Barar: I mean the page downloads the script file but doesn't execute it. Yes, if you want the full code :
<!-- Google Code for Formulaire Contact Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = [...];
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "[...]";
var google_remarketing_only = false;
/* ]]> */
</script>
<!-- <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"></script> -->
<script type="text/javascript" src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js');
$("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&script=0');
}
});
</script>
<div style="display:inline;">
<img id="google_conversion" height="1" width="1" style="border-style:none;" alt="" src="#"/>
</div>
In the long run you'd be better off using the proper asynchronous version of the adwords conversion script I think as it has been built specifically to handle these sorts of things. This way avoids any encoding mistakes and is easier to read and maintain.
So, based on this here is what I reckon you'd want (although I am no jQuery expert - I prefer to use standard javascript but hey each to their own):
<head>
<!-- Add the async conversion script as usual - use async if you want --->
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion_async.js" charset="utf-8"></script>
</head>
<!-- the rest of your site HTML and code -->
<script>
$(function() {
if ([condition]) {
window.google_trackConversion({
google_conversion_id: "[...]",
google_conversion_language: "en",
google_conversion_format: "3",
google_conversion_color: "ffffff",
google_conversion_label: "[...]",
google_conversion_value: 0,
google_remarketing_only: false
});
}
});
</script>
Try This:
<script type="text/javascript">
$(document).ready(function(){
if ([condition]) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.googleadservices.com/pagead/conversion.js";
document.getElementsByTagName("head")[0].appendChild(script);
}
});
</script>
Try this:
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js', function() {
$("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&script=0');
});
}
});
This doesn't set the src of #google_conversion until after the conversion.js script is loaded. If there's a dependency, you need to do them in the right order. You were doing this first, because $.getScript is asynchronous.
My Javascript/html code looks like following which works great and shows country name in Part 1 below.
When i am trying to convert the code in .JS file it doesnt work means doesnt shows the country name in Part 2.. not sure what is wrong in the code
Part 1
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</body>
Part 2
// JavaScript Document
document.write("<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'></script>");
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
document.write("<script type='text/javascript' src='http://smart-ip.net/geoip-json?callback=GetUserInfo'></script>");
Here is the HTML of PArt 2
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude </title>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</table>
Include the jQuery reference as a real script tag in your HTML still - and remove the document.write.
Also ; on the end of your var list... Perhaps.
Your <head> tag should be
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude
</title>
<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'>
</script>
<script src="test.js" type="text/javascript"></script>
</head>
As Paul notes document.write is deprecated. You should always try to include <script> tags rather than manipulating the DOM. I think that the way you were doing it would mean that the jQuery code in your file would be executing before jQuery had loaded - due to the fact that you are writing the tag directly to the DOM immediately before your code. So there will not have been time to parse it. I would think that this code would have raised an error in fact.