5

How can I load a JavaScript with this code

<script type="text/javascript" src="http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869"></script>

after page has loaded

$(document).ready(function() 
 {

 }); 

Is there another way?

0

5 Answers 5

14

Try appending the script to the head section: (Working jsFiddle)

$(document).ready(function(){
    $('<script/>',{type:'text/javascript', src:'http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869'}).appendTo('head');
 }); 

EDIT: I like this syntax better..

4
  • if i want use it in a sample div i should use $(#sample).apeend ... ?! Feb 21, 2014 at 22:12
  • @user3261715 what is this code meant for? is it a plugin, library, etc?
    – Yotam Omer
    Feb 21, 2014 at 22:14
  • no i just use this code on a div advertise area! Feb 21, 2014 at 22:25
  • @user3261715 I'm not really sure I get you.. there's not much meaning to placing a script inside a specific div.. can you give an example of what would the javascript file look like? (now it's blank)
    – Yotam Omer
    Feb 21, 2014 at 22:43
3

I prefer to create the script tag, then its type and src attribs like this:

var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);

Straightforward and semantic.

0
1

Put your script tags after all of the HTML content.

1

By using the ajax() function as follows:

$(document).ready(function() {
    $.ajax({
        url: "http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869",
        dataType: "script",
        cache: true
    });
});
1

You can use jQuery's getScript() method to achieve this. Documentation here. Usage:

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});
1
  • 1
    This is what I originally had, but I did a double-check and remembered that this method adds a time-stamp to the URL preventing caching. As such, you need to use the low-level $.ajax() function in order to leverage browser caching.
    – dana
    Feb 21, 2014 at 23:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.