I need to dynamically load script wrapped like this:
{
(function () {
"use strict";
function myFunction() {
// code
}
myFunction();
})();
}
I i use jquery function $.getScript() script is loaded, but no executed. (in webmaster tools i can see request and response - script is here with content)
How i can load and automaticly execute script like this?
I was solve this problem with another ajax request not to javascript file but to html file (html response) with basic tag script with url address. Also with passed some variables into it.
So my html looks like this:
<script type="text/javascript">
var varPassedToScript = 1;
</script>
<script type="text/javascript" src="https://www.urlToScript.com/script.js"></script>
And it works...
If anybody have better solution - i'm curious
Related
I have a div which looks like
<div>
//Useful content
<script type="text/javascript">
function(){
//some useful code
}
</script>
</div>
Now am getting this div as a response of an Ajax call and appending that into body. Now when the gets appended to body, the function inside the script tag should get executed. But not.. what is the problem here?
You should be using document.createElement("script"); if you need to insert some script dynamically. This is recommended approach.
Anyway, following code is working just fine for me:
var str = "<script>alert('Hi!');</scr"+"ipt>";
$('#container').append($(str)[0]);
Make sure you escape you script properly.
Your function is not executing because it is not being called.
You should use a self-executing function that will just run as soon as it's loaded:
(function() {
alert('hello world!');
})();
I want append script in head if there is tag <script> in the body, i try as following but it don't work, How can done it?
DEMO: http://jsfiddle.net/rYXJx/
JS:
var TAREA = $('body').find('textarea').length;
if(TAREA > 0){
$('head').append('<script type="text/javascript" src="files/js/nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>');
};
You can use jquery getScript function:
http://api.jquery.com/jQuery.getScript/
so the correct code looks like the below:
$.getScript('files/js/niceEdit.js');
One of the problems in your script is that the </script> inside the string literal actually breaks the outer <script> tag. You might notice these characters in your page which seem to come out of nowhere:
');};
Secondly, while it is still possible to inject a <script> tag in the head, there is no direct/easy/cross-browsr way of knowing when the script has finished loading. And you cannot use a script before it is loaded completely.
Best solution is to use jQuery.getScript() which provides a callback. Use the callback to call nicEditors.allTextAreas() function:
$(document).ready(function () {
if ($("textarea").length > 0) {
$.getScript("files/js/nicEdit.js", function () {
// no need for onDomLoaded -- DOM is loaded at this point!
nicEditors.allTextAreas();
});
}
});
From script within body I dynamically load jquery and SimpleModal into page header. I use callback to be sure jQuery is fully loaded before making calls into it--this works. However when I dynamically load the SimpleModal script file, I can't subsequently call its methods. It appears when the SimpleModal script lazy loads it is unable to reference the current document object. Any help would be greatly appreciated.
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
/******** Main function ********/
function main() {
jQuery(document).ready(function ($) {
var domain = 'http://qo.microssoftware.com';
/******* Load SimpleModal *******/
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
domain + "/js/simplemodal.js");
script_tag.onload = modalLoadHandler;
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
});
}
function modalLoadHandler() {
/******* Open Modal *******/
$.modal("<div><h1>SimpleModal</h1></div>", {});
}
Try:
<script type="text/javascript" src="http://qo.microssoftware.com/js/simplemodal.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$.modal("<div><h1>SimpleModal</h1></div>");
});
</script>
OR, if you want to call the modal using your main() function:
<script type="text/javascript" src="http://qo.microssoftware.com/js/simplemodal.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
function main() {
$.modal("<div><h1>SimpleModal</h1></div>");
}
});
</script>
You don't need to put the js in the header... Actually some programmers always put all their JS just before the ending BODY-tag.
I would suggest that this is unnecessary, to begin with. The simplemodal script is very compact. Give more consideration to how to optimize script loading in general (gzip, or if you must go ajax, AMD dependency loading with RequireJS or the like) without the unnecessary complication of this kind of ajax method.
The script loaders that use this type of method (like the Facebook SDK or Google Maps) will search the window (global) element for a callback to call once the script is initialized. Basically, you would have to modify the simplemodal code and then wrap your dependent code in a callback. I hardly see how that could be necessary in this case.
This is where you would want to create an async-closure based around the onload event of the script.
If you must support ancient IE, you can also hook into the onreadystatechange event, the same way you would do it in AJAX requests (in pure JS).
The more-modern browsers won't fire this event.
So turn the onload into a callback, which fires known methods from the file.
You can get around errors by also attaching to the onerror of the script's loading.
I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.
Basically my app work like that :
Index.php manage call to other pages.
Each page contains 2 function onLoad() and onClose() which are redefined in each page
Index.php call the pages and execute the onLoad
Basically, i preload the page in a hidden div, i execute the predefined $.onLoad function and the i put the loaded content into a visible div
My question is only about the onLoad() scope, i want to remove code from the jquery eval seq when i change page, but i need a way to define it in the page.php file without knowing the container
The eval/seq is probably the eval queue of jquery, can't found info about that, just obtain with firebug...
In 2 words, i would like to be able to remove injected dom and script when i change context (pages)
index.php
$.onLoad = function() {}
$("#blabla").onChange(function() {
$("#data_iframe").load(chaineUrl, {}, function(responseText, textStatus, XMLHttpRequest) {
$("#data_iframe").ready(function() {
$("#data_div").children().remove();
$.onLoad();
$("#data_iframe").children().hide().appendTo($("#data_div")).show(); $("#data_iframe").children().remove();
$.onLoad = undefined;
}
});
});
page.php
<script>
$.onClose = (function(){
$('#container').blablabla();
//alert("test");
});
$.onLoad = (function(){
$('#container').blablabla();
}
</script>
The problem is that the jquery EVAL/SEQ keep growing each time a page is opened
and there are some side-effect like calling multiple time a function...
I guess its a scope problem so can you help me correct my code
(i've try with or without the $ but doesn't change anything)
just for information
<div id="data_div"></div>
<div id="data_iframe"></div>
Thanks
I usually use $(document).ready instead of onload. No need to do the "onload" trigger in load complete function. The ready function within the page.php will do the same job.
And how about direct load into data_div?
index.php
$("#blabla").onChange(function() {
$("#data_div").load(page.php);
});
page.php
<script>
$(document).ready(function() {
$('#container').blablabla();
});
</script>
I didn't try page close function before, may be it is not what you want. But you can try:
<script>
$(document).ready(function() {
$('#container').blablabla();
$(window).unbind('unload');
$(window).unload(function(){
$('#container').blablabla();
//alert("test");
})
});
</script>